Cancel a Parallel Loop
Parallel.For
andParallel.ForEach
methods support cancellation through the use of cancellation tokens.- Set
CancellationToken
in theParallelOptions
parameter passed to parallel loop and then enclose the parallel call in a try-catch block.
Sample
int[] nums = Enumerable.Range(0, 10000000).ToArray();
CancellationTokenSource cts = new CancellationTokenSource();
ParallelOptions po = new ParallelOptions();
po.CancellationToken = cts.Token;
// Run a task so that we can cancel from another thread.
Task.Factory.StartNew(async () =>
{
await Task.Delay(10);
cts.Cancel();
});
try
{
Parallel.ForEach(nums, po, (num) =>
{
double d = Math.Sqrt(num);
});
}
catch (OperationCanceledException e)
{
Console.WriteLine(e.Message);
}
finally
{
cts.Dispose();
}