O'Reilly logo

C# Multithreaded and Parallel Programming by Rodney Ringler

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

Canceling a PLINQ

Canceling a parallel query is very similar to canceling a task using TPL. First, we create a cancellation token and then we issue a cancel request to the cancellation token. This will create an operation cancellation exception. Then when we execute our parallel query, add the parallel extension method WithCancellation(), and pass it the cancellation token. Then, finally, we catch the operation cancellation request and process it.

The .NET framework does not pass a single OperationCanceledException into a System.AggregateException; the OperationCanceledException must be processed in a separate catch block.

How to do it

Now, let's open our PLINQQuery project again and this time we will add a Cancel button and work with the btnMethod2_Click ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required