Sunday, February 26, 2017

How to cancel a Parallel.For and Parallel.Foreach loop – Task Parallel Library


In my previous article, I explained about Parallel.For and Parallel.Foreach loop in detail. In this article I will explain, how to cancel running or ongoing Parallel.For and Parallel.Foreach loop on certain event.

Parallel.For and Parallel.Foreach has overload methods to pass ParallelOptions to accept cancel request from user. We need to set CancelationToken to ParallelOptions and pass it to Parallel.For and Parallel.Foreach methods. When user request for cancelling parallel loop via cancellation token, then the parallel loop will throw an OperationCanceledException and cancel the parallel loop. See below example for more information.

Code –


Output –




As you can see in above example, when user request for cancel the parallel loop, cancellation token of parallel options will throw an OperationCanceledException and cancel the running parallel loop.


References –

See also –