Thursday, November 12, 2009

Parallel.For for .NET 3.x

.NET 4.0 includes an interesting class called Parallel, with a For method that allows the iterations of a for loop to be executed concurrently, like this:

Parallel.For(0, 10, i => Console.WriteLine(i));

I’ve done a lot of multithreading over the years, but I must confess it’s never occurred to me to apply concurrency in this way, at the level of a simple for loop.   I’m not sure how often I’ll use it in practice, but my current work project is .NET 3.5 so I wanted to have a .NET 3.x version of Parallel.For to play with.   The code is shown below. 

Some basic tests reveal that at the extremes the performance is not as good as the .NET 4.0 version, but for more common scenarios it seems to be comparable.  

static class Parallel30
    public static void For(int fromInclusive, int toExclusive, Action<int> action)
        using (var doneEvent = new ManualResetEvent(false))
            int iterations = (toExclusive - fromInclusive);
            int iterationsCompleted = 0;
            Exception actionEx = null;

            WaitCallback iterationCode =
                (arg) =>
                    catch (Exception ex)
                        actionEx = ex;

                    int completed = Interlocked.Increment(ref iterationsCompleted);
                    if (completed == iterations)

            for (int i = fromInclusive; i < toExclusive; i++)
                ThreadPool.QueueUserWorkItem(iterationCode, i);


            if (actionEx != null)
                throw new Exception("Action failed", actionEx);



Post a Comment

<< Home