一任务的取消 [英] Cancellation of a task

查看:191
本文介绍了一任务的取消的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图在一个任务的取消象下面

I tried to run a simple example on the cancellation of a task like the one below

CancellationTokenSource tokenSource2 = new CancellationTokenSource();

CancellationToken token2 = tokenSource2.Token;


Task task2 = new Task(() =>
{
    for (int i = 0; i < int.MaxValue; i++)
    {
        token2.ThrowIfCancellationRequested();
        Thread.Sleep(100);
        Console.WriteLine("Task 2 - Int value {0}", i);
    }
}, token2);

task2.Start();

Console.WriteLine("Press any key to cancel the task");
Console.ReadLine();

tokenSource2.Cancel();
Console.WriteLine("Task 2 cancelled? {0}", task2.IsCanceled);

我预计 Console.WriteLine(任务2取消{0}?,task2.IsCanceled); 将打印 **任务2取消了?真正的** ,但它印的

I expected that Console.WriteLine("Task 2 cancelled? {0}", task2.IsCanceled); would print **"Task 2 cancelled? True"**, but it printed "False".

你知道发生了什么事?那是预期的行为?谢谢你。

Do you know what happened? Is that the expected behaviour? Thanks.

编辑:保证任务未完成取消请求调用之前。我加了到Console.ReadLine()

to ensure that the task hasn't completed before the cancellation request is called. I added the Console.ReadLine().

推荐答案

首先,也许你误解了 IsCanceled 意味着什么?这并不意味着这个工作正在等待取消,所以应该很快完成,就意味着这个工作已被取消,现在是完整的。

First, maybe you misunderstand what IsCanceled means? It doesn't mean "this Task is pending cancellation, so it should complete shortly", it means "this Task has been canceled, it is now complete".

如果你没有误会,想想事件完全相同的顺序。什么情况是这样的:

If you didn't misunderstand that, think about what exactly the sequence of events is. What happens is this:

  1. ThrowIfCancellationRequested()被调用,但令牌不取消呢,所以它不会抛出。
  2. 的Thread.Sleep()被调用,因此运行工作线程处于休眠状态。
  3. 取消()之称。
  4. IsCanceled 检查。在code。在工作没有机会认识到,令牌被取消了,所以它仍然在运行,所以 IsCanceled 返回
  5. ThrowIfCancellationRequested()再次调用,这一次罚球,这实际上取消工作
  1. ThrowIfCancellationRequested() is called, but the token wasn't canceled yet, so it doesn't throw.
  2. Thread.Sleep() is called, so the thread running the Task sleeps.
  3. Cancel() is called.
  4. IsCanceled is checked. The code in the Task didn't have a chance to realize that the token was canceled, so it's still running, so IsCanceled returns false.
  5. ThrowIfCancellationRequested() is called again, this time it throws, which actually cancels the Task.

这就是为什么 ISCanceled 将返回给你。如果你希望它返回,您可以添加类似 Thread.sleep代码(150)前检查 IsCanceled ,或者甚至更好,实际上等待工作来完成。

This is why ISCanceled is returning false to you. If you want it to return true, you could add something like Thread.Sleep(150) before checking IsCanceled, or, even better, actually wait for the Task to complete.

这篇关于一任务的取消的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆