创建CancellationTokenSource对象用于取消Task

时间:2022-01-28 20:36:02

  虽然使用线程池ThreadPool让我们使用多线程变得容易,但是因为是由系统来分配的,如果想对线程做精细的控制就不太容易了,比如某个线程结束后执行一个回调方法。恰好Task可以实现这样的需求。这篇文章我从以下几点对Task进行总结。

  1. 认识Task
  2. Task的用法

Task类在命名空间System.Threading.Tasks下,通过Task的Factory返回TaskFactory类,以TaskFactory.StartNew(Action)方法可以创建一个新的异步线程,所创建的线程默认为后台线程,不会影响前台UI窗口的运行。

如果要取消线程,可以利用CancellationTakenSource对象。如果要在取消任务后执行一个回调方法,则可以使用Task的()方法。

利用Task对之前的例子进行重写和扩展。代码如下。

namespace ThreadDemo
{
class Program
{
static void Main(string[] args)
{
// 创建CancellationTokenSource对象用于取消Task
CancellationTokenSource cancelTokenSource = new CancellationTokenSource(); Fish fish1 = new Fish() { Name = "小黄鱼", Score = };
Fish fish2 = new Fish() { Name = "大鲨鱼", Score = }; // 创建一个Task
Task task1 = new Task(() => fish1.Move(cancelTokenSource.Token), cancelTokenSource.Token);
task1.Start(); // Task1被取消后的回调方法(小黄鱼被击中后显示积分)
task1.ContinueWith(fish1.ShowScore); Task task2 = new Task(() => fish2.Move(cancelTokenSource.Token), cancelTokenSource.Token);
task2.Start();
task2.ContinueWith(fish2.ShowScore); // 按任意键发射
Console.ReadKey(); // 武器工厂线程池
Gun gun = new Gun();
LaserGun laserGun = new LaserGun();
TaskFactory taskFactory = new TaskFactory();
Task[] tasks = new Task[]
{
taskFactory.StartNew(()=>gun.Fire()),
taskFactory.StartNew(()=>laserGun.Fire())
}; // 执行武器开火
taskFactory.ContinueWhenAll(tasks, (Task) => { }); cancelTokenSource.Cancel();
Console.ReadKey();
}
} /// <summary>
/// 鱼
/// </summary>
public class Fish
{
public string Name { get; set; } public int Score { get; set; } public Fish()
{
} public void Move()
{
Console.WriteLine(string.Format("{0}在游来游去...", Name));
} /// <summary>
/// 游动
/// </summary>
/// <param name="cancelToken"></param>
public void Move(CancellationToken cancelToken)
{
while (!cancelToken.IsCancellationRequested)
{
Console.WriteLine(string.Format("{0}在游来游去...", Name)); // 阻塞1秒
Thread.Sleep();
}
} /// <summary>
/// 中枪后显示奖励
/// </summary>
/// <param name="task"></param>
public void ShowScore(Task task)
{
Console.WriteLine(string.Format("{0}中弹了,你得到{1}分",Name,Score));
}
}
}

程序运行结果如下:

aaarticlea/png;base64,iVBORw0KGgoAAAANSUhEUgAAAbkAAAFeCAIAAACXd/ZFAAAgAElEQVR4nO2cd7weRdXHn3/F8tp97YqoiFIURVBKROkgvYUiVTohCSUJIdxAIJ2EhCQQSkJC6L1JSXQRlK5GY+8tiAoGCCkQ3n3/GBzm7sw5c2Z2Zve59/6+n/3cz+7smTOz+9z93rP7PM/tlAAAAFh6eno6y37yGBYsWLBgYRa4EgsWLFj8yxuuXG+DE+ssb/7kSW/+5Elv+dRJb/nUyW/59Mlv/fTJb93wlLdteMrbPnPq/6hloyFv32jI2z875B2fPe0dnzvtnZ877Z0bD33nxkPftcmwd20y7N2bDHv3psPfs+nw92w2/D2bnf7ez5/+3s+f8b4vnPG+L5zxv5ufqZb3f/Gs93/xrA986awPfGnEB7cY8cEtRn7wyyM/9OWRH9py1Ie3HPXhLUd9ZKuzP7LV2R/5yuiPfmX0R786+mNfPedjW5/z8a3P+fg2Yz6+zZj1txmz/rbnfmLbcz+xXc8G2/VsMKhng0FjP/m1sZ/82thPbX/ep7Y/79NfP18tG35j3IbfGPeZHcZ9ZocLNtrxgo12vGCjnS787E4Xfnbn8Z/befzndh6/8S4TNt5lwsa7Tthk14mb7DZx090mbbr7pM12n7TZHpM322Py5/eY/PlvTvnCN6d8Yc8pm+85dfO9pm6+10Vf3PuiL+590Zf2mfalfaZtsc+0LfadvsW+07+838Vf3u/iLfe/eMv9Z2x1wIytDpix1YEzv3LgzK8cOPOrB13y1YMu2frgWVsfPGvrwbO2GTx7m0Nmb3vI7G0PnbPdoXO2O+zS7Q67dNBhlw46/LKvHX7Z17512fbfmrv9EXO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YNCLXhlI5Er1FhI1NlyJpd8vqCu7/KdenLJaFu7Ksix7enrM/H5X6rfb+d8eLFj68YK6sjt/mitq8fpKsihRhrnS/GgSNTZciaXfL6gru/ynXihlyV1pitLMj7oSCxb/grqyO3+aK2qpWVeWVkUZ4MpleF6JZcAvqCu7/Kde6jyvrIgy+HmlngH/24MFSz9eUFd2509zRS3R74Pboox0JTM2XIml3y+oK7v8p/wVdC6UKM38cCUWLP4FdWV3/jRXJK+gcxclyspAcCUWLP4FdWWX/5S/gpWFEaX/HrxHTGg8AH0X1JVd+DPCV3JR9vCuBABQtK4G/Kz8jHgFg0RJunKZoJTFggULloGzOFxZAgAAsKi6EgsWLFiwUAtciQULFiz+paenpxP9ziAAAAwcOhneMAQAgP7G/wNylSkbwuIG5QAAAABJRU5ErkJggg==" alt="" />

eg2:

C# 使用 CancellationTokenSource 终止线程

使用CancellationTokenSource对象需要与Task对象进行配合使用,Task会对当前运行的状态进行控制(这个不用我们关心是如何孔控制的)。而CancellationTokenSource则是外部对Task的控制,如取消、定时取消。

下面我们来看看示例代码

  1. class Program
  2. {
  3. //声明CancellationTokenSource对象
  4. static CancellationTokenSource cancelTokenSource = new CancellationTokenSource();
  5. //程序入口
  6. static void Main(string[] args)
  7. {
  8. Task.Factory.StartNew(MyTask, cancelTokenSource.Token);
  9. Console.WriteLine("请按回车键(Enter)停止");
  10. Console.ReadLine();
  11. cancelTokenSource.Cancel();
  12. Console.WriteLine("已停止");
  13. Console.ReadLine();
  14. }
  15. //测试方法
  16. static void MyTask()
  17. {
  18. //判断是否取消任务
  19. while (!cancelTokenSource.IsCancellationRequested)
  20. {
  21. Console.WriteLine(DateTime.Now);
  22. Thread.Sleep(1000);
  23. }
  24. }
  25. }

运行效果如图

创建CancellationTokenSource对象用于取消TaskTask.Factory.StartNew 创建并启动了 MyTask 方法,并传递了一个 CancellationTokenSource.Token 对象进去。我们可以通过在外部CancellationTokenSource对象进行控制是否取消任务的运行

当在 MyTask 中的 cancelTokenSource.IsCancellationRequested 判断如果是取消了任务的话 就跳出while循环执行。也就结束了任务

我们还可以使用计时取消任务,当一个任务超过了我们所设定的时间然后自动取消该任务的执行。如下代码所示

  1. var cancelTokenSource = new CancellationTokenSource(3000);

除了构造函数,我们还可以使用另外一种方式实现定时取消,如下代码所示

  1. cancelTokenSource.CancelAfter(3000);

运行起来效果是一样的,3秒钟定时取消。

多个 CancellationTokenSource 复合

在有多个CancellationTokenSource需要一起并行管理的时候,比如任意一个任务取消 则取消所有任务。我们不必去一个一个的去关闭,只需要将需要一起并行关闭的CancellationTokenSource组合起来就行了。如下代码所示,执行结果是跟上面的图一样的。我就不再上图了。

  1. class Program
  2. {
  3. //声明CancellationTokenSource对象
  4. static CancellationTokenSource c1 = new CancellationTokenSource();
  5. static CancellationTokenSource c2 = new CancellationTokenSource();
  6. static CancellationTokenSource c3 = new CancellationTokenSource();
  7. //使用多个CancellationTokenSource进行复合管理
  8. static CancellationTokenSource compositeCancel = CancellationTokenSource.CreateLinkedTokenSource(c1.Token, c2.Token, c3.Token);
  9. //程序入口
  10. static void Main(string[] args)
  11. {
  12. Task.Factory.StartNew(MyTask, compositeCancel.Token);
  13. Console.WriteLine("请按回车键(Enter)停止");
  14. Console.ReadLine();
  15. //任意一个 CancellationTokenSource 取消任务,那么所有任务都会被取消。
  16. c1.Cancel();
  17. Console.WriteLine("已停止");
  18. Console.ReadLine();
  19. }
  20. //测试方法
  21. static void MyTask()
  22. {
  23. //判断是否取消任务
  24. while (!compositeCancel.IsCancellationRequested)
  25. {
  26. Console.WriteLine(DateTime.Now);
  27. Thread.Sleep(1000);
  28. }
  29. }
  30. }

以上代码调用了c1.Cancel();触发了MyTask()方法中的compositeCancel.IsCancellationRequested为true,则取消了任务。所以我们在所有任务中判断复合的这个CancellationTokenSource对象即可。