views:

59

answers:

4

What is the advantage of using a ConcurrentBag(Of MyType) against just using a List(Of MyType)? The MSDN page on the CB (http://msdn.microsoft.com/en-us/library/dd381779(v=VS.100).aspx) states that

ConcurrentBag(Of T) is a thread-safe bag implementation, optimized for scenarios where the same thread will be both producing and consuming data stored in the bag

So what is the advantage? I can understand the advantage of the other collection types in the Concurrency namespace, but this one puzzled me.

Thanks.

+1  A: 

Unlike the other concurrent collections, ConcurrentBag<T> is optimized for single-threaded use.
Unlike List<T>, ConcurrentBag<T> can be used from multiple threads simultaneously.

SLaks
+1  A: 

I think you should read that as "where multiple threads access the container and each thread may both produce and/or consume data", it is definitely intended for parallel scenarios.

Henk Holterman
+4  A: 

The biggest advantage here is that ConcurrentBag<T> is safe to access from multiple threads while LisT<T> is not. If thread safe access is important for your scenario then a type like ConcurrentBag<T> is possibly to your advantage over List<T> + manual locking. We'd need to know a bit more about your scenario before we can really answer this question.

Additionally List<T> is an ordered collection while ConcurrentBag<T> is not.

JaredPar
+5  A: 

Internally, the ConcurrentBag is implemented using several different Lists, one for each writing thread, typically.

What that statement you quoted means is that, when reading from the bag, it will prioritize the list created for that thread. Meaning, it will first check the list for that thread before risking contention on another thread's list.

This way it can minimize lock contention when multiple threads are both reading and writing. When the reading thread doesn't have a list, or it's list is empty, it has to lock a list assigned to a different thread. But, if you have multiple threads all reading from and writing to their own list, then you won't ever have lock contention.

Mike
+1, this is the correct explanation. Also see: http://www.codethinked.com/post/2010/01/27/NET-40-and-System_Collections_Concurrent_ConcurrentBag.aspx
Hans Passant