Sunday, July 25, 2010

ConcurrentBag<T> - Thread Safe Collections

.Net 4.0 introduces a new namespace, System.Collections.Concurrent, this namespace contains a set of collections that would be very much useful in threaded programming.
The Add or Remove methods of List<T> is not thread safe, meaning that if you are adding or removing items from a list which is accessed from multiple threads, you will end up overwriting some of the items.
So, in multi threading programming, you would need to lock the list before adding or removing items from it.

The ConcurrentBag<T&gt in the System.Collections.Concurrent is a thread safe collections i.e all you have to do is call Add or Remove in the usual way and the collection will take care of adding the items without overwriting them.

Here is an example using the ConcurrentBag<T&gt with the Parallel Task Library...

ConcurrentBag array = new ConcurrentBag();
Parallel.For(0, 100000, i =>
//Do some work here


catch (AggregateException e)
foreach (Exception ex in e.InnerExceptions)


The ConcurrentBag resembles the List in that it is unordered and contain duplicate values and also accept a null as valid value for a reference type.

The System.Collection.Concurrent namespace also contains other implementation of thread safe collections, to name a few,ConcurrentStack, ConcurrentDictionary, ConcurrentQueue...

No comments:

Post a Comment