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