In my Parallel.ForEach loop i have some objects that I need to initialize in the “local init” lambda.
If one of these objects fails to initialize, I would like to terminate the entire parallel loop.
What is the best way to do this?
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();
});
The best way to do this (with out seeing any code), would be to check if the object you attempted to initialise is
null, if it is,break().I hope this helps.
Edit. Following some comments,
stop()might be the better option in this case.