.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> 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> with the Parallel Task Library...
ConcurrentBag array = new ConcurrentBag();
try
{
Parallel.For(0, 100000, i =>
{
//Do some work here
array.Add(i);
});
}
catch (AggregateException e)
{
Console.WriteLine("\n\n\n\n");
foreach (Exception ex in e.InnerExceptions)
{
Console.WriteLine(ex.Message);
}
}
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...
Comments
Post a Comment