【问题标题】:Got "Index out of bounds" Error on List.Add() in c# Parallel.ForEach在 c# Parallel.ForEach 中的 List.Add() 上出现“索引越界”错误
【发布时间】:2012-08-15 22:09:53
【问题描述】:

这里是代码

List<string> something = new List<string>();
Parallel.ForEach(anotherList, r =>
     {
            .. do some work
             something.Add(somedata);
      });

每百次运行大约 1 次出现 Index out of bounds 错误。有没有办法防止线程引起的冲突(我假设)?

【问题讨论】:

标签: c# .net


【解决方案1】:

为了防止出现此问题,您可以在并行部分中使用 ConcurrentQueue 或类似的并发集合来代替 List。并行任务完成后,您可以将其放入List&lt;T&gt;

有关更多信息,请查看 System.Collections.Concurrent 命名空间,以找到适合您用例的集合。

【讨论】:

  • Bingo,我现在用的是ConcurrentStack,它有Push()PushRange(),非常有用。还有一个ToList() 来完成
【解决方案2】:

我发现lock (yourObject)也否定了线程问题

【讨论】:

  • 您基本上否定了 Parallel.Foreach 方法的好处。我确信使用并发对象是使用锁对象的最佳解决方案。
猜你喜欢
  • 2015-01-10
  • 2021-05-17
  • 2016-08-26
  • 2014-06-06
  • 2015-03-22
  • 2013-10-13
  • 2014-01-27
相关资源
最近更新 更多