简体   繁体   English

.NET 4.5.1跟踪所有取消任务?

[英].NET 4.5.1 Track all Tasks for Cancellation?

5 unrelated class instances do Task.Run() to start 1-4 instances that "do stuff". 5个不相关的类实例执行Task.Run()以启动1-4个“执行任务”的实例。 Each Task has a CancellationToken. 每个任务都有一个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. 如果这是.NET 2.0的日子,我可能会在另一个AppDomain中开始工作,然后杀死该AppDomain以停止子工作或类似的工作。 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. 我还想到,子Task可能会在Timer间隔上检查一个静态类,以查看是否应该停止,但是我想尽可能避免将责任从生成的Task中排除。

If possible and/or applicable, use the same CancellationToken for each of the tasks, and just request cancellation via the CancellationTokenSource . 如果可能和/或适用,则对每个任务使用相同的CancellationToken ,并仅通过CancellationTokenSource请求CancellationTokenSource If each task has its own CancellationToken to support individual cancellation, you can use the following strategy instead: 如果每个任务都有其自己的CancellationToken以支持单个取消,则可以改用以下策略:

  1. Create a CancellationTokenSource instance which you can use to issue a cancel request to all tasks. 创建一个CancellationTokenSource实例,您可以使用该实例向所有任务发出取消请求。
  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. 启动任务时,每个任务都以CancellationTokenSource.CreateLinkedTokenSource开头,它为您提供一个CancellationToken ,一旦任何输入被取消,它就进入取消状态。

This allows you to preserve the original individual cancellation support as well as use a CancellationTokenSource for global cancellation. 这使您可以保留原始的单个取消支持,也可以使用CancellationTokenSource进行全局取消。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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