Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

When a ConcurrentBag is better than a List?

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?

like image 959
ab_732 Avatar asked Aug 25 '11 16:08

ab_732


1 Answers

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:

Any instance members are not guaranteed to be thread safe.

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 is what you should use for this, which is thread-safe for multiple readers and writers.

like image 96
Judah Gabriel Himango Avatar answered Oct 10 '22 03:10

Judah Gabriel Himango