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

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

相关文章:

  • 2022-12-23
  • 2022-12-23
  • 2022-12-23
  • 2022-12-23
  • 2022-12-23
  • 2021-11-27
  • 2021-07-31
  • 2021-06-23
猜你喜欢
  • 2021-08-28
  • 2021-08-04
  • 2022-12-23
  • 2021-11-20
  • 2021-11-25
  • 2021-08-13
相关资源
相似解决方案