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 –


  1. Truely a very good article on how to handle the future technology. After reading your post,thanks for taking the time to discuss this, I feel happy about and I love learning more about this topic. keep sharing your information regularly for my future reference. This content creates a new hope and inspiration with in me. Thanks for sharing article like this. The way you have stated everything above is quite awesome. Keep blogging like this. Thanks.

    Best Dental Clinic In Annanagar

  2. This is an awesome post.Really very informative and creative contents.These concept is a good way to enhance the knowledge.I like it and help me to development very well.Thank you for this brief explanation and very nice information.Well, got a good knowledge.

    Hadoop Training in Chennai

  3. Great post!I am actually getting ready to across this information,i am very happy to this commands.Also great blog here with all of the valuable information you have.Well done,its a great knowledge.
    Cat Coaching in Chennai

  4. This blog is having the general information. Got a creative work and this is very different one.We have to develop our creativity mind.This blog helps for this. Thank you for this blog. This is very interesting and useful.

    Fresher Jobs in Mumbai
    Fresher Jobs in Pune
    Fresher Jobs in Noida
    Fresher Jobs in Hyderabad