How to cancel parallel loops in .NET C#
April 30, 2014 Leave a comment
Cancelling parallel loops in C# is similar to cancelling “normal” tasks. You will need to supply a ParallelOptions object to the parallel loop assigning a cancellation token to its CancellationToken property. If you don’t know these objects then make sure to check out the following posts:
When you cancel the cancellation token then no new iterations will be started in a parallel loop. However, those already running will finish. Parallel.For and Parallel.ForEach will then throw an OperationCanceledException.
Declare the cancellation token:
CancellationTokenSource cancellationTokenSource = new CancellationTokenSource();
Create a Task that will cancel the token after 5 seconds:
Task.Factory.StartNew(() =>
{
Thread.Sleep(5000);
cancellationTokenSource.Cancel();
Console.WriteLine("Token cancelled");
});
Define the parallel loop options and assign the cancellation token:
ParallelOptions parallelLoopOptions =
new ParallelOptions()
{
CancellationToken = cancellationTokenSource.Token
};
Perform some loop that is guaranteed to take more than 5 seconds:
try
{
Parallel.For(0, Int64.MaxValue, parallelLoopOptions, index =>
{
double result = Math.Pow(index, 3);
Console.WriteLine("Index {0}, result {1}", index, result);
Thread.Sleep(100);
});
}
catch (OperationCanceledException)
{
Console.WriteLine("Cancellation exception caught!");
}
Run the code and you’ll see that the parallel loop will likely run for slightly more than 5 seconds which is because loops running when the cancellation token is cancelled will be allowed to complete.
View the list of posts on the Task Parallel Library here.