Parallel的陷阱

时间:2022-07-03 01:59:22
var nums = Enumerable.Range(,).ToArray();
int total = ;
Parallel.For<int>(
fromInclusive: ,
toExclusive: nums.Length,
/* 陷阱 */
localInit: () => ,
body: (i, loopState, subtotal) =>
{
return subtotal + nums[i];
},
localFinally: i => Interlocked.Add(ref total, i)
);
Console.WriteLine("total={0}",total);
localInit会根据启动的线程来调用多次。

如果只启用了一个线程,结果是11,二个是否2