C# : PLINQ and Task Parallel Library, part 2

Hello,

Following my previous post on PLINQ and TPL (C# : PLINQ and Task Parallel Library), Yves Dubois, one of my friends remarked that I had use the list collection in my TPL examples.

As he mentioned, List isn’t thread safe. You can read about it here: List Class under Thread Safety.

We could use a locking mechanism, but .Net 4 introduced the System.Collections.Concurrent namespace which provides thread safe collections out of the box. How convenient !

Here is an example of incorrect code from my previous post:

public IEnumerable<int> ParallelForCalculatePrimes(int maxValue)
{
    var primeNumbers = new List<int>();

    Parallel.For(1, maxValue + 1, number =>
    {
        if (IsPrime(number))
            primeNumbers.Add(number);
    });

    return primeNumbers;
}

As you can see the List primeNumbers is updated in my call to Parallel.For. If you check the output of the list and compare it to the non parallel version, you can see that this leads to errors in the resulting collection instance.

The solution would be to use a concurrent collection like ConcurrentBag, which is an unordered thread-safe collection. All public and protected members of this collection are guaranteed to be thread-safe.

public IEnumerable<int> ParallelForCalculatePrimes(int maxValue)
{
    var primeNumbers = new ConcurrentBag<int>();

    Parallel.For(1, maxValue + 1, number =>
    {
        if (IsPrime(number))
            primeNumbers.Add(number);
    });

    return primeNumbers;
}

A change so small you might have missed it. The only change was changing the type of primeNumbers from List to ConcurrentBag.

2 thoughts on “C# : PLINQ and Task Parallel Library, part 2

  1. As you just said a change so small. What is the performance cost? Is being thread safe a big hit on performance?

    1. With my non-precise measurements the numbers are pretty much the same. A few hundredths of a second apart, which considering the precision of my measurements isn’t significant.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s