问题描述
我正在使用Parallel.Foreach填充外部ConcurrentBag.我还尝试使用通用列表,但一切正常.
I am using a Parallel.Foreach for populating an external ConcurrentBag. I tried also to use a common List and everything works fine.
我很幸运还是错过了ConcurrentBag的特殊范围?
I have been lucky or I missed the special scope of ConcurrentBag?
推荐答案
您很幸运; Parallel.ForEach
填充列表不是线程安全的,最终会遇到问题.
You have been lucky; Parallel.ForEach
to populate a List is not thread-safe, you will eventually run into problems.
根据MSDN,List<T>
不是线程安全的:
According to MSDN, List<T>
is not thread safe:
列表< T>可以同时支持多个阅读器,只要 集合未修改.通过集合枚举是 本质上不是线程安全的过程.在极少数情况下 枚举涉及一个或多个写访问,这是唯一的方法 确保线程安全是在整个过程中锁定集合 枚举.允许多个人访问该集合 读写线程,您必须实现自己的 同步.
A List<T> can support multiple readers concurrently, as long as the collection is not modified. Enumerating through a collection is intrinsically not a thread-safe procedure. In the rare case where an enumeration contends with one or more write accesses, the only way to ensure thread safety is to lock the collection during the entire enumeration. To allow the collection to be accessed by multiple threads for reading and writing, you must implement your own synchronization.
您应该使用ConcurrentBag,它对多个读取器和写入器都是线程安全的.
ConcurrentBag is what you should use for this, which is thread-safe for multiple readers and writers.
这篇关于什么时候ConcurrentBag比List更好?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!