Canceling parallel work
In this section, we will work with some examples of canceling parallel operations. There are a few operations that fall into this realm. There are static parallel operations that are part of the System.Threading.Tasks.Parallel
class and there are PLINQ operations. Both of these types use a CancellationToken
property, as we used in our managed threading example in the previous section. However, handling the cancellation request is slightly different. Let’s look at an example to understand the differences.
Canceling a parallel loop
In this section, we will create a sample that illustrates how to cancel a Parallel.For
loop. The same method of cancellation is leveraged for the Parallel.ForEach
method. Perform the following steps:
- Open the
CancelThreadsConsoleApp
project from the previous section. - In the
ManagedThreadsExample
class, create a newProcessTextParallel
method with the following implementation:public static void ProcessTextParallel...