Skip to content

Latest commit

 

History

History
43 lines (31 loc) · 2.86 KB

how-to-cancel-a-task-and-its-children.md

File metadata and controls

43 lines (31 loc) · 2.86 KB
title description ms.date dev_langs helpviewer_keywords ms.assetid
How to: Cancel a Task and Its Children
See examples of how to cancel a task and its children in .NET. The examples cover steps from cancelable task creation, to the notice that the task was canceled.
04/09/2024
csharp
vb
tasks, how to cancel
08574301-8331-4719-ad50-9cf7f6ff3048

How to: Cancel a Task and Its Children

These examples show how to perform the following tasks:

  1. Create and start a cancelable task.

  2. Pass a cancellation token to your user delegate and optionally to the task instance.

  3. Notice and respond to the cancellation request in your user delegate.

  4. Optionally notice on the calling thread that the task was canceled.

The calling thread does not forcibly end the task; it only signals that cancellation is requested. If the task is already running, it is up to the user delegate to notice the request and respond appropriately. If cancellation is requested before the task runs, then the user delegate is never executed and the task object transitions into the Canceled state.

Example

This example shows how to terminate a xref:System.Threading.Tasks.Task and its children in response to a cancellation request. It also shows that when a user delegate terminates by throwing a xref:System.Threading.Tasks.TaskCanceledException, the calling thread can optionally use the xref:System.Threading.Tasks.Task.Wait%2A method or xref:System.Threading.Tasks.Task.WaitAll%2A method to wait for the tasks to finish. In this case, you must use a try/catch block to handle the exceptions on the calling thread.

[!code-csharpTPL_Cancellation#04] [!code-vbTPL_Cancellation#04]

The xref:System.Threading.Tasks.Task?displayProperty=nameWithType class is fully integrated with the cancellation model that is based on the xref:System.Threading.CancellationTokenSource?displayProperty=nameWithType and xref:System.Threading.CancellationToken?displayProperty=nameWithType types. For more information, see Cancellation in Managed Threads and Task Cancellation.

See also