我的问题是:parallel.for中的第三个参数,它是做什么的?
当我将其更改为 ()=> 1d 时,它会使我的结果加倍,设置为 2 时它会增加三倍,但它会忽略小数。
如果它是某种加倍,为什么它会忽略小数?那里到底发生了什么?
我现在尝试添加锁。而且它不只是将 interimresult 初始化为指定的值。
这是我使用的代码:
static void RunParallelForCorrectedAdam()
{
object _lock = new object();
double result = 0d;
// Here we call same method several times.
// for (int i = 0; i < 32; i++)
Parallel.For(0, 32,
// Func<TLocal> localInit,
() => 3d,
// Func<int, ParallelLoopState, TLocal, TLocal> body,
(i, state, interimResult) =>
{
lock (_lock)
{
return interimResult + 1;
}
},
//Final step after the calculations
//we add the result to the final result
// Action<TLocal> localFinally
(lastInterimResult) =>
{
lock (_lock)
{
result += lastInterimResult;
}
}
);
// Print the result
Console.WriteLine("The result is {0}", result);
}