This example uses Parallel.For
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;
Parallel.For(1, 10001,
() => 0, // initial value,
(num, state, localSum) => num + localSum,
localSum => Interlocked.Add(ref total, localSum));
return total; // total = 50005000
}