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
时间: 2024-10-11 20:31:23