UnhandledCanceledException on throw from Parallel.ForEach

I am trying to allow the cancellation of a Parallel.ForEach loop. According to this MSDN article , perhaps I follow their coding.

 // Tokens for cancellation ParallelOptions po = new ParallelOptions(); po.CancellationToken = cts.Token; try { Parallel.ForEach(queries, po, (currentQuery) => { // Execute query ExecuteQuery(currentQuery); // Throw exception if cancelled po.CancellationToken.ThrowIfCancellationRequested(); // *** }); } catch (OperationCanceledException cancelException) { Console.WriteLine(cancelException.Message); } 

However, when I call cts.Cancel(); from a function available to the user, the application crashes in the line marked with asterisks above with an error:

 System.OperationCanceledException was unhandled by user code Message=The operation was canceled. Source=mscorlib StackTrace: at System.Threading.CancellationToken.ThrowIfCancellationRequested() at CraigslistReader.SearchObject.<>c__DisplayClass7.<bw_DoWork>b__5(Query currentQuery) in {PATH}:line 286 at System.Threading.Tasks.Parallel.<>c__DisplayClass2d`2.<ForEachWorker>b__23(Int32 i) at System.Threading.Tasks.Parallel.<>c__DisplayClassf`1.<ForWorker>b__c() InnerException: 

I have an Exception handler right there, so I don't understand the crash. Any ideas?

+7
source share
1 answer

The problem is that po.CancellationToken.ThrowIfCancellationRequested(); explicitly throws an exception that is not handled. The exception handler may be around calling Parrallel.ForEach() , but the exception is not handled in the lambda expression. Either delete the line, or add an exception handler to the lambda expression, and it should work.

See Cancel task - this is an exception for more information.

+2
source

All Articles