问题来了
long sum = 0;
Parallel.For(1, 10000, y => { sum1 += y;} );
解决方案是..
Parallel.For<int>(0, result.Count, () => 0, (i, loop, subtotal) =>
{
subtotal += result[i];
return subtotal;
},
(x) => Interlocked.Add(ref sum, x)
);
如果这段代码中有两个参数。例如
long sum1 = 0; long sum2 = 0;
Parallel.For(1, 10000, y => { sum1 += y; sum2=sum1*y; } );
我们要做什么?我猜必须使用数组!
int[] s=new int[2];
Parallel.For<int[]>(0, result.Count, () => s, (i, loop, subtotal) =>
{
subtotal[0] += result[i];
subtotal[1] -= result[i];
return subtotal;
},
(x) => Interlocked.Add(ref sum1, x[0])
//but how about sum2 i tried several way but it doesn't work.
//for example like that
//(x[0])=> Interlocked.Add (ref sum1, x[0])
//(x[1])=> Interlocked.Add (ref sum2, x[1]));
);
最佳答案
我不确定我能否解决您的问题,因为我真的不知道它是什么。但是 Parallel.For
不容易支持这样的累加器是有充分理由的:因为尝试并行化具有副作用的简单操作是荒谬的。
Parallel.For
用于并行化相对昂贵的操作,这些操作没有相互依赖的副作用。常规的 for 循环(或 Accumulate
)是正确的做法。
关于c# - 并行地。对于股票值(value)大于一个,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2907048/