Skip to content

Latest commit

 

History

History
30 lines (22 loc) · 2.14 KB

how-to-cancel-a-parallel-for-or-foreach-loop.md

File metadata and controls

30 lines (22 loc) · 2.14 KB
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
csharp
vb
parallel foreach loop, how to cancel
parallel for loops, how to cancel
9d19b591-ea95-4418-8ea7-b6266af9905b

How to: Cancel a Parallel.For or ForEach Loop

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.

Example

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.

See also