C#取消令牌作为任务第二个参数 [英] C# cancellation tokens as task second argument

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

问题描述

如何通过转发任务内部而不是任务调用方法内部的令牌来取消长时间运行的任务?

How can I cancel a long running task by forwarding the token inside the task rather than inside the method the task is calling?

我的代码:

class Program
{
    static void Main(string[] args)
    {
        CancellationTokenSource token = new CancellationTokenSource();
        Stopwatch stop = new Stopwatch();
        stop.Start();

        Task.Factory.StartNew(() => myLongTask(6000), token.Token);

        while (true)
        {
            Thread.SpinWait(1000);
            if (stop.ElapsedMilliseconds > 3000)
            {
                token.Cancel();
            }
        }
    }

    public static void myLongTask(int time)
    {
        var sw = Stopwatch.StartNew();
        Console.WriteLine("Task started");
        while (true)
        { }
        Console.WriteLine("Task ended");
    }
}

此任务永远不会被取消.如果我在 myLongTask()方法中转发令牌,则可以在取消触发后连续收听,但是,我不确定...该怎么做?

This task never gets cancelled. If I forward the token within myLongTask() method I can listen continuously if the cancellation was triggered, however, I am not sure... How can you do it in this way?

推荐答案

您需要亲自检查令牌的状态,例如:

You need to check the state of the token yourself, for example:

public static void myLongTask(int time, CancellationToken token)
{
    var sw = Stopwatch.StartNew();
    Console.WriteLine("Task started");
    while (true)
    { 
      token.ThrowIfCancellationRequested();
    }
    Console.WriteLine("Task ended");
}

如评论中所述,这样做的原因是取消是一种合作行为.并不是那时框架将不得不强制您的任务停止,这可能会使您的应用程序处于不良状态.通过检查自己,您可以完全控制取消操作的含义.

The reason for this, as mentioned in the comments, it that cancellation is a co-operative action. It it wasn't then the framework would have to force your task to stop, and this could leave your application in an undesirable state. By checking yourself you have full control over what it means to cancel an operation.

这篇关于C#取消令牌作为任务第二个参数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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