C#:取消任务无效(CancellationTokenSource)

问题描述 投票:0回答:1

我有一些长时间运行的代码,我想作为Task运行并在需要时使用CancellationTokenSource取消,但是取消似乎不起作用,因为当调用tokenSource.Cancel()时我的任务一直在运行(不会引发异常)。

可能缺少明显的东西?

以下剪切示例:

bool init = false;

private void Button1_Click(object sender, EventArgs e)
{
    CancellationTokenSource tokenSource = new CancellationTokenSource();
    CancellationToken token = tokenSource.Token;
    Task task = new Task(() =>
    {
        while (true)
        {
            token.ThrowIfCancellationRequested();

            if (token.IsCancellationRequested)
            {
                Console.WriteLine("Operation is going to be cancelled");
                throw new Exception("Task cancelled");
            }
            else
            {
                // do some work
            }
        }
    }, token);

    if (init)
    {
        tokenSource.Cancel();
        button1.Text = "Start again";
        init = false;
    } else
    {
        try
        {
            task.Start();
        } catch(Exception ex)
        {
            Console.WriteLine(ex.ToString());
        }
        button1.Text = "Cancel";
        init = true;
    }
}
c# .net winforms task-parallel-library
1个回答
0
投票
代码中的主要问题是您没有存储tokenSource。第二次Button1_Click调用取消的令牌与您在第一次调用时传递给任务的令牌不同。

第二个问题是您一次又一次地创建新任务,但是您的逻辑建议您希望一个任务应该在第一次单击时创建,并在第二次单击时终止。

© www.soinside.com 2019 - 2024. All rights reserved.