Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Parallel.Foreach exceptions and cancel

I have tried to find out how exceptions and cancel work for Parallel.Foreach. All examples seems to deal with Tasks.

What happens on an exception in Parallel.Foreach?
- Do I wrap the entire loop in try/catch(AggregateException)?
- Will all other tasks in the loop, even tasks not started yet, run to completion before the exception is caught?

Same questions for CancelationToken

like image 279
adrianm Avatar asked Feb 22 '11 08:02

adrianm


People also ask

How do you handle exceptions in parallel ForEach?

For and Parallel. ForEach overloads do not have any special mechanism to handle exceptions that might be thrown. In this respect, they resemble regular for and foreach loops ( For and For Each in Visual Basic); an unhandled exception causes the loop to terminate as soon as all currently running iterations finish.

How do I cancel parallel ForEach?

ForEach methods support cancellation through the use of cancellation tokens. For more information about cancellation in general, see Cancellation. In a parallel loop, you supply the CancellationToken to the method in the ParallelOptions parameter and then enclose the parallel call in a try-catch block.

Is parallel ForEach blocking?

No, it doesn't block and returns control immediately. The items to run in parallel are done on background threads.


1 Answers

In short, exception in each loop is aggregated and presented under AggregateException. Whenever exception occurs, loops that are started are allowed to complete but no further loops will be started. ForEach does have many overloads that allow one to have local init & finally blocks and body action also takes ParallelLoopState that loop body code can use to check for exception occurance on another loop and then break it self cooperatively if needed.

See this article that provides additional information

like image 84
VinayC Avatar answered Oct 13 '22 18:10

VinayC