Overview
Cancellation is achieved by:
- Supplying a
CancellationToken
to theParallel.For
orParallel.ForEach
method’sParallelOptions
parameter - Enclosing the parallel call in a
try-catch
block
Example
int[] nums = Enumerable.Range(0, 1_000_000).ToArray();
using CancellationTokenSource cts = new();
ParallelOptions po = new();
po.CancellationToken = cts.Token;
try
{
Parallel.ForEach(nums, po, (num) =>
{
double d = Math.Sqrt(num);
Console.WriteLine($"{d} on {Thread.CurrentThread.ManagedThreadId}");
});
}
catch
{
…
}