首页 > 解决方案 > CancellationToken 甚至为空

问题描述

在我的应用程序中,我运行 aTask执行繁重的操作,我试图停止执行该Task. 实际上,我在课堂上声明了以下结构:

public class Foo
{
    private CancellationTokenSource tokenSource = new CancellationTokenSource();
    private CancellationToken token;

    public void Start()
    {
        var task = new Task(async () => {
           try
           {
               await new Bot().StartAsync(token);
           }
           catch(Exception ex)
           {
              Console.WriteLine(ex.ToString());
           }
        }, token));

        task.Start();
    }
}

如您所见,我已经声明了一个CancellationTokenSource允许我在用户单击按钮时停止任务执行:

StopTask_Click(object sender, EventArgs e) 
{
    tokenSource.Cancel();
}

现在,在该StartAsync方法中,我有以下代码:

public async Task StartAsync(CancellationToken token)
{
    ApplicationToken = token;

    while(true)
    {
       if(ApplicationToken.IsCancellationRequested)
       {
           break;
       }
    }
}

ApplicationToken作为参数传递的令牌存储在StartAsync方法类中。

在按钮单击事件之后,请求应该被取消但没有任何反应。

然后我检查每次迭代是否有取消请求,但变量值为 even false

标签: c#task

解决方案


嗯,看来你忘了token = tokenSource.Token;

Edit1:您应该使用检查取消ThrowIfCancellationRequested()

编辑2:

using System;
using System.Threading;
using System.Threading.Tasks;

namespace CancellationTokenPOC
{
class Program
{
    public static async Task Main(string[] args)
    {
        Console.WriteLine("Hello World!");

        TokenPOC t = new TokenPOC();
        var longRunningTask = Task.Factory.StartNew(async () =>
        {
            for (int i = 0; i < 10; i++)
            {
                Console.WriteLine(i);
                t.token.ThrowIfCancellationRequested();

                await Task.Delay(10000);
            }

        });
        Console.ReadKey();
        t.source.Cancel();
        await Task.Delay(1000);
        Console.WriteLine("finishing");
    }
}

class TokenPOC
{
    public CancellationTokenSource source = new CancellationTokenSource();
    public CancellationToken token;
    public TokenPOC()
    {
        token = source.Token;
    }
}
}

该令牌被取消并按预期结束程序......


推荐阅读