This web site uses cookies. By using the site you accept the cookie policy.This message is for compliance with the UK ICO law.

Parallel and Asynchronous
.NET 4.0+

Synchronisation in Parallel Loops

The fifth part of the Parallel Programming in .NET tutorial continues the description of parallel loops. This article looks at the synchronisation problems of aggregation in parallel loops and how to overcome them with locking and local state values.

Local Loop State in For Loops

Thread-local state can be used in Parallel.For loops in a similar manner to Parallel.ForEach using an overload with five parameters. The first two parameters determine the lower and upper bounds of the loop. The remaining three parameters define the initialisation delegate, the loop's body and the final action delegate.

The code below shows a parallel For loop that gives the same results as the previous ForEach example.

object sync = new object();
long total = 0;

Parallel.For(1, 100000001,
    () => 0L,
    (value, pls, localTotal) =>
        return localTotal += value;
    localTotal =>
        lock (sync)
            total += localTotal;

// total = 5000000050000000
1 September 2011