[英]Parallel.ForEach local finally without partition
In C# Parallel.ForEach localFinally gets called for each partition and not for each iteration, how can we make it to get called for each iteration and not for a partition? 在C#Parallel.ForEach中,localFinally为每个分区而不是每个迭代调用,我们如何使它为每个迭代而不是一个分区调用?
In below example, if we run it it just add one item in the results collection even if trades collection, and hence the iteration, has more than 1 item in it. 在下面的示例中,如果我们运行它,即使交易集合(因此迭代中有多个项目)也只会在结果集合中添加一项。
Parallel.ForEach(trades, parallelOptions,
// Loop Init
() =>
{
var result= new Result();
return result;
},
// Loop Body
(trade, loopState, index, result) =>
{
result= new Result();
return result;
},
// Loop Completion
result=>
{
lock (_lockObj)
{
results.Add(result);
Interlocked.Add(ref count, 1);
}
});
How do we make above local finally to get called for each iteration? 我们如何使局部最终高于每次迭代?
localInit - The function delegate that returns the initial state of the local data for each task. localInit-返回每个任务的本地数据初始状态的函数委托。
body - The delegate that is invoked once per iteration. body-每次迭代调用一次的委托。
localFinally - The delegate that performs a final action on the local state of each task. localFinally-对每个任务的本地状态执行最终操作的委托。
For each partition, 对于每个分区,
localInit
is called once 一次调用localInit
body
is called zero or more times, depending on how many items the partition processes. body
被称为零次或多次,具体取决于分区处理的项目数。 localFinally
is called once localFinally
被调用一次 You need to do your per-item logic in body
. 您需要在body
执行每项逻辑。 If you want to aggregate the results, you should keep a local list for each partition. 如果要汇总结果,则应为每个分区保留一个本地列表。
Parallel.ForEach(trades, parallelOptions,
// Loop Init
() =>
{
// This creates one list per partition
return new List<Result>(); // Becomes list
},
// Loop Body
(trade, loopState, index, list) =>
{
// Only add the results to the local list for this partition
list.Add(new Result());
return list;
},
// Loop Completion
list=>
{
lock (_lockObj)
{
// Merge the local list from each partition into the shared results list
results.AddRange(list);
Interlocked.Add(ref count, list.Count);
}
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.