简体   繁体   中英

.NET 4.5.1 Track all Tasks for Cancellation?

5 unrelated class instances do Task.Run() to start 1-4 instances that "do stuff". Each Task has a CancellationToken. What is a cool or smart way to have another object stop all of those spawned Tasks without touching/affecting their spawning objects? If this was the .NET 2.0 days I might start things in another AppDomain and then kill the AppDomain to stop the child work, or something similar. It also occurred to me that the child Task might check a static class on a Timer interval to see if it should stop, but I want to keep the responsibility out of the spawned Tasks if possible.

If possible and/or applicable, use the same CancellationToken for each of the tasks, and just request cancellation via the CancellationTokenSource . If each task has its own CancellationToken to support individual cancellation, you can use the following strategy instead:

  1. Create a CancellationTokenSource instance which you can use to issue a cancel request to all tasks.
  2. When you start your tasks, start each with a CancellationTokenSource.CreateLinkedTokenSource that provides you with a CancellationToken that enters the canceled state as soon as any of the inputs is canceled.

This allows you to preserve the original individual cancellation support as well as use a CancellationTokenSource for global cancellation.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM