Thursday, May 05, 2011

Why doesn't ConcurrentBag implement ICollection?

Hopefully you’ve encountered by now the System.Collections.Concurrent namespace. It’s new to .NET 4, and it has many useful data structures which are optimized for multi-threaded usage. ConcurrentBag, for instance, is an unordered collection of objects, which multiple threads can add and remove objects from at the same time.

Recently I needed to test that some piece of code was thread-safe. To do that, I wanted to run it once synchronically, and once asynchronically. It looked something like that:

private static IEnumerable<ComputationResult> ComputeSynchronous(IEnumerable<string> inputs)
{
Console.WriteLine("Starting synchrnous correction.");            
var results = new ConcurrentBag<ComputationResult>();
foreach (var input in inputs)
{       
//Some more printouts and work here
var result = computation.Compute(input);                
//Some more printouts and work here
results.Add(result);                
}
return results;

And so, the first method computes stuff in one thread, and the second does the same computation on the same inputs, but inside a parallel loop. This is all nice and simple, but I was a little bothered by the fact the the code inside the loop in the two methods repeats itself. The logical conclusion would be to extract a method, of course. This should look something like this:

Read more: Doron's .NET Space