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
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.
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.
No, it doesn't block and returns control immediately. The items to run in parallel are done on background threads.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With