title | description | ms.date | dev_langs | helpviewer_keywords | ms.assetid | ||||
---|---|---|---|---|---|---|---|---|---|
How to: Cancel a Parallel.For or ForEach Loop |
Cancel a Parallel.For or Parallel.ForEach loop in .NET by supplying a cancellation token object to the method in the ParallelOptions parameter. |
08/18/2023 |
|
|
9d19b591-ea95-4418-8ea7-b6266af9905b |
The xref:System.Threading.Tasks.Parallel.For%2A?displayProperty=nameWithType and xref:System.Threading.Tasks.Parallel.ForEach%2A?displayProperty=nameWithType methods support cancellation through the use of cancellation tokens. For more information about cancellation in general, see Cancellation. In a parallel loop, you supply the xref:System.Threading.CancellationToken to the method in the xref:System.Threading.Tasks.ParallelOptions parameter and then enclose the parallel call in a try-catch block.
The following example shows how to cancel a call to xref:System.Threading.Tasks.Parallel.ForEach%2A?displayProperty=nameWithType. You can apply the same approach to a xref:System.Threading.Tasks.Parallel.For%2A?displayProperty=nameWithType call.
[!code-csharpTPL_Parallel#29] [!code-vbTPL_Parallel#29]
If the token that signals the cancellation is the same token that is specified in the xref:System.Threading.Tasks.ParallelOptions instance, then the parallel loop will throw a single xref:System.OperationCanceledException on cancellation. This immediately stops all iterations from executing as the exception is thrown. If some other token causes cancellation, the loop will throw an xref:System.AggregateException with an xref:System.OperationCanceledException as an InnerException
.