.NET Framework Parallel.ForEach


Example

This example uses Parallel.ForEach to calculate the sum of the numbers between 1 and 10000 by using multiple threads. To achieve thread-safety, Interlocked.Add is used to sum the numbers.

using System.Threading;

int Foo()
{
    int total = 0;
    var numbers = Enumerable.Range(1, 10000).ToList();
    Parallel.ForEach(numbers, 
        () => 0, // initial value,
        (num, state, localSum) => num + localSum,
        localSum => Interlocked.Add(ref total, localSum));
    return total; // total = 50005000
}