Parallel.For
suggest changeThis 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 }
Found a mistake? Have a question or improvement idea?
Let me know.
Table Of Contents