相关疑难解决方法(0)

当我使用 CancelAfter() 时,任务仍在运行

我想使用 CancellationTokenSource 停止任务。我的测试如下:

测试 1:使用 Cancel() 成功停止了任务。

测试 2:使用 CancelAfter() 没有停止任务,为什么?

任务动作是:

    static Action testFun = () => {
        Thread.Sleep(4000); // or other a long time operation
        Console.WriteLine("Action is end");
    };
Run Code Online (Sandbox Code Playgroud)

测试1代码:

        CancellationTokenSource source = new CancellationTokenSource(); 
        CancellationToken token = source.Token;
        //Register the cancel action
        token.Register(() =>
        {
            Console.WriteLine("Task is canceled");
        });
        Task task = new Task(testFun, token); 
        task.Start();
        source.Cancel();     
        Console.ReadLine();
Run Code Online (Sandbox Code Playgroud)

输出是:

Task is canceled
Run Code Online (Sandbox Code Playgroud)

测试2代码:

        CancellationTokenSource source = new CancellationTokenSource(); 
        CancellationToken token = source.Token;
        //Register the cancel action
        token.Register(() …
Run Code Online (Sandbox Code Playgroud)

c# asynchronous task

4
推荐指数
1
解决办法
6623
查看次数

标签 统计

asynchronous ×1

c# ×1

task ×1