CSharp Parallel Programming

Last Updated: 3/9/2022

Cancel a Parallel Loop

  • Parallel.For and Parallel.ForEach methods support cancellation through the use of cancellation tokens.
  • Set CancellationToken in the ParallelOptions 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();
}

Example