In my previous article, I explained about Parallel.For and
Parallel.Foreach loop in detail. In this article I will explain, how to cancel running
or ongoing Parallel.For and Parallel.Foreach loop on certain event.
Parallel.For and Parallel.Foreach has overload methods to pass ParallelOptions to accept cancel request from user. We need to set CancelationToken
to ParallelOptions and pass it to Parallel.For and Parallel.Foreach methods.
When user request for cancelling parallel loop via cancellation token, then the parallel loop will throw an OperationCanceledException and cancel the parallel loop. See below example for
more information.
Code –
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
using System.Collections.Generic; | |
using System.Diagnostics; | |
using System.Linq; | |
using System.Text; | |
using System; | |
using System.Threading.Tasks; | |
using System.Threading; | |
namespace ParallelFor | |
{ | |
class Program | |
{ | |
static void Main(string[] args) | |
{ | |
using (CancellationTokenSource cancelToken = new CancellationTokenSource()) | |
{ | |
//Setting cancellationtoken to parallel options | |
ParallelOptions options = new ParallelOptions(); | |
options.CancellationToken = cancelToken.Token; | |
Console.WriteLine("Press 'c' to cancel."); | |
//running another thread to get user cancel request | |
Task.Factory.StartNew(() => | |
{ | |
if (Console.ReadKey().KeyChar == 'c') | |
cancelToken.Cancel(); | |
}); | |
try | |
{ | |
Console.Write("Starting Parallel.For loop"); | |
Parallel.For(0, 100000, options, (i) => | |
{ | |
Console.Write("{0}, ", i); | |
options.CancellationToken.ThrowIfCancellationRequested(); | |
}); | |
} | |
catch (OperationCanceledException ex) | |
{ | |
Console.ForegroundColor = ConsoleColor.Red; | |
Console.WriteLine("Parallel loop has been canceled by user"); | |
} | |
catch (Exception e) | |
{ | |
throw (e); | |
} | |
} | |
Console.ReadLine(); | |
} | |
} | |
} |
Output –
As you can see in above example, when user request for
cancel the parallel loop, cancellation token of parallel options will throw an OperationCanceledException
and cancel the running parallel loop.
References –
See also –
Parallel.For and Parallel.Foreach – TPL
How to handle exception in Parallel.For and Parallel.Foreach loop? – TPL
How to handle exception in Parallel.For and Parallel.Foreach loop? – TPL