在我的Parallel.ForEach
循环中,我有一些需要在“本地初始化”lambda 中初始化的对象。如果这些对象之一无法初始化,我想终止整个并行循环。做这个的最好方式是什么?
Parallel.ForEach(collection,
() => //local init
{
var localObjects= CreateObjects();
foreach (var obj in localObjects)
if (!obj.Initialize())
// want to terminate the entire parallel loop here!!
return localObjects;
}
(element, loopState, localObjects) => // loop body
{
// some code here
},
localObjects => // local finally
{
foreach (var obj in localObjects)
obj.Terminate();
});