December 2019
Intermediate to advanced
346 pages
9h 8m
English
Just like normal tasks, we can use the CancellationToken class to cancel the Parallel.For and Parallel.ForEach loops. When we cancel the token, the loop will finish the current iterations that may be running in parallel but will not start new iterations. Once the existing iterations finish, the parallel loops throw OperationCanceledException.
Let's look at this with an example. First, we'll create a cancellation token source:
CancellationTokenSource cancellationTokenSource = new CancellationTokenSource();
Then, we'll create a task that cancels the token after five seconds:
Task.Factory.StartNew(() =>{ Thread.Sleep(5000); cancellationTokenSource.Cancel(); Console.WriteLine("Token has been cancelled"); ...Read now
Unlock full access