这是代码
List<string> something = new List<string>();
Parallel.ForEach(anotherList, r =>
{
.. do some work
something.Add(somedata);
});
我每百次运行大约 1 次收到Index out of bounds
错误。有没有办法防止线程引起的冲突(我假设)?
为了防止此问题,您可以在并行部分中使用ConcurrentQueue
或类似的并发集合,而不是列表。并行任务完成后,您可以将其放入List<T>
中。
有关更多信息,请查看 System.Collections.Concurrent 命名空间,以查找适合您的用例的集合。
我发现lock (yourObject)
也否定了线程问题