In the previous article, we introduced how to Break and Stop loops, and how to define local variables of a thread. This article describes how to cancel loops and handle exceptions externally.
Cancel
In a parallel loop, you can pass the aspx> CancellationToken in the ParallelOptions parameter to cancel loop control. We can pass CancellationTokenSource to the Cancellation value of the ParallelOptions object after instantiation. The following is an example:
02 |
public void CancelLoop() |
04 |
var sourceNums = Enumerable.Range(0, 1000000000); |
05 |
var cts = new CancellationTokenSource(); |
06 |
var po = new ParallelOptions(); |
07 |
var stack = new ConcurrentStack<int>(); |
08 |
po.CancellationToken = cts.Token; |
09 |
po.MaxDegreeOfParallelism = System.Environment.ProcessorCount; |
10 |
Task.Factory.StartNew(() => |
12 |
foreach (var num in sourceNums) |
21 |
Parallel.ForEach(sourceNums,po, num => |
24 |
po.CancellationToken.ThrowIfCancellationRequested(); |