Skip to main content
 首页 » 编程设计

c#之任务未按预期取消

2024年02月06日11lori

我们得到了以下场景:

class Program 
{ 
    static void Main(string[] args) 
    { 
        // trigger the delayed function 
        trigger(); 
 
        // cancel the running task. 
        _token.Cancel(); 
 
        // keep window open ;-) 
        Console.ReadLine(); 
 
    } 
 
    private static CancellationTokenSource _token = null; 
    private static async void trigger() 
    { 
        _token = new CancellationTokenSource(); 
 
        try 
        { 
            // run task 
            await Task.Run(async () => 
            { 
                // wait time 
                await Task.Delay(2500); 
 
                // we should be cancelled here !! 
                Console.WriteLine(string.Format("IsCancellationRequested={0}", _token.Token.IsCancellationRequested)); 
                Console.WriteLine("SHOULD NOT HAPPEN"); 
 
            }, _token.Token); 
        } 
        catch (TaskCanceledException) 
        { 
        } 
    } 
} 

IMO 预期的行为是任务的操作主要在处理完 Task.Delay(2500) 之后取消。

但是控制台正在打印:

IsCancellationRequested=True 
SHOULD NOT HAPPEN 

这感觉就像是一个错误。如果您将 CancellationToken 作为参数添加到 Task.Delay - 函数,它将按预期工作。

那么,如果任务中的函数使用 Task.Delay,您可能不知道如何处理取消?

请您参考如下方法:

.Net 中的取消是合作的。将 token 作为参数传递给 Task.Run 只会将 token 与返回的任务相关联。

要真正取消任务,您需要检查任务本身内部的 token 。如果您希望在延迟内取消任务,您需要将 token 传递给 Task.Delay 方法。否则你只能在延迟之前或之后检查 while:

await Task.Run(async () => 
{ 
    _token.Token.ThrowIfCancellationRequested(); 
    await Task.Delay(2500, _token.Token); 
    _token.Token.ThrowIfCancellationRequested(); 
     
    Console.WriteLine(string.Format("IsCancellationRequested={0}", _token.Token.IsCancellationRequested)); 
    Console.WriteLine("SHOULD NOT HAPPEN"); 
 
}, _token.Token);