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 |
|
|
08574301-8331-4719-ad50-9cf7f6ff3048 |
These examples show how to perform the following tasks:
-
Create and start a cancelable task.
-
Pass a cancellation token to your user delegate and optionally to the task instance.
-
Notice and respond to the cancellation request in your user delegate.
-
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.
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.
- xref:System.Threading.CancellationTokenSource?displayProperty=nameWithType
- xref:System.Threading.CancellationToken?displayProperty=nameWithType
- xref:System.Threading.Tasks.Task?displayProperty=nameWithType
- xref:System.Threading.Tasks.Task%601?displayProperty=nameWithType
- Task-based Asynchronous Programming
- Attached and Detached Child Tasks
- Lambda Expressions in PLINQ and TPL