取消令牌的使用 [英] Usage of Cancellation Token

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

问题描述

我正在尝试学习如何使用取消令牌取消任务。
在这里,我已经为此编写了一个UnitTest,但是我没有得到它的工作方式。

I am trying learn how to cancel Task using cancellation token. Here, I have written a UnitTest for it but I am not getting the way it is working.

[TestMethod]
public async Task Task_should_not_run_when_token_cancelled_before_its_call()
{
    var cts = new CancellationTokenSource();
    var token = cts.Token;

    cts.Cancel();

    Debug.WriteLine("Calling Cancellable Method".ToUpper());
    try
    {
        await CheckMeCalled(token);
    }
    catch (Exception expException)
    {

    }
}

private async Task CheckMeCalled(CancellationToken ct)
{
    Debug.WriteLine("Before task delayed".ToUpper());
    await Task.Delay(5000);
    Debug.WriteLine("After task delayed".ToUpper());
}

在上述测试中,我称为 cts。在调用 CheckMeCalled 方法之前,先取消()。因此它不应在取消后运行。

In the above test, I called the cts.Cancel() before calling the CheckMeCalled method. so it should not run as it canceled. But it is running to the full extent.

我在某处读到:


如果Task未运行并且您将其取消,则它将不会进入运行状态,而是在您调用它时进入取消状态。

If Task is not running and you cancel it then it will not go to a running state instead it go for canceled state when you call it.

但是,这似乎没有发生。有人会向我解释吗?

But it is not seems to be happening here. Would somebody explain it to me?

推荐答案

您添加的报价与创建新的 Task 通过 Task.Run Task.Factory.Startnew 。将 CancellationToken 传递给您的方法时,必须在运行前主动检查令牌

The quote you added was related to creating a new Task via Task.Run or Task.Factory.Startnew. When passing a CancellationToken to your method, you have to actively check the token before running

private async Task CheckMeCalled(CancellationToken ct)
{
    ct.ThrowIfCancellationRequested();
    Debug.WriteLine("Before task delayed".ToUpper());
    await Task.Delay(5000, ct);
    Debug.WriteLine("After task delayed".ToUpper());
}

以下是斯蒂芬·图布(Stephan Toub)关于取消令牌和任务:

Here is a quote by Stephan Toub regarding cancellation token and Task:


如果令牌在任务开始执行之前已请求取消,则任务无法执行。它会立即转换为已取消,而不是转换为正在运行。

我还建议阅读< a href = http://blogs.msdn.com/b/pfxteam/archive/2009/05/22/9635790.aspx rel = nofollow> NET 4取消框架进行了广泛的回顾PFX小组的取消机制

I also recommend reading NET 4 Cancellation Framework for a broad review of the cancellation mechanism by the PFX Team

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

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