本示例用于Parallel.ForEach通过使用多个线程来计算 1 到 10000 之间的数字之和。为了实现线程安全,Interlocked.Add用于对数字求和。
using System.Threading;
int Foo()
{
int total = 0;
var numbers = Enumerable.Range(1, 10000).ToList();
Parallel.ForEach(numbers,
() => 0, // 初始值,
(num, state, localSum) => num + localSum,
localSum => Interlocked.Add(ref total, localSum));
return total; // 总计 = 50005000
}