I am using a Parallel.Foreach for populating an external ConcurrentBag. I tried also to use a common List and everything works fine.
I have been lucky or I missed the special scope of ConcurrentBag?
I am using a Parallel.Foreach for populating an external ConcurrentBag. I tried also to use a common List and everything works fine.
I have been lucky or I missed the special scope of ConcurrentBag?
If you're using
Parallel.ForEach
to populate aList<T>
and everything is working just fine then you're simply getting lucky. TheForEach
method can and will run your code on multiple threads so any communication outside theForEach
must be with objects that can handle concurrent updates.List<T>
cannot butConcurrentBag<T>
can.ConcurrentBag is the correct answer, only in .NET 4.0 it is very slow. This has been fixed in .NET 4.5. See http://ayende.com/blog/156097/the-high-cost-of-concurrentbag-in-net-4-0
Both ConcurrentStack and ConcurrentQueue will also work in your situation...
You have been lucky;
Parallel.ForEach
to populate a List is not thread-safe, you will eventually run into problems.According to MSDN,
List<T>
is not thread safe:ConcurrentBag is what you should use for this, which is thread-safe for multiple readers and writers.