Search code examples
c#exceptiontask-parallel-libraryparallel.foreachcancellation

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 CancellationToken.


Solution

  • 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 occurrence on another loop and then break it self cooperatively if needed.

    See this article that provides additional information