首页 > 解决方案 > 如何安全地取消任务?

问题描述

所以我有这个任务,从点击一个按钮开始,我想知道,我如何安全地取消这个任务的循环?

private async Task RunAsync()
{
    PerformanceCounter counter = new PerformanceCounter("Process", "% Processor Time", pServer.ProcessName, true);
    Random r = new Random();
    while (true)
    {
        float pct = counter.NextValue() / 10f;
        ServerCPU = pct.ToString("0.0");
        await Task.Delay(2000);
    }
}

单击启动任务循环的按钮后,我将如何取消它?

标签: c#.netasynchronousasync-awaittask

解决方案


与处理 s 时不同,如果没有它的合作,Thread你不能取消/中止 a 。Task这就是发挥作用CancellationToken的地方。CancellationTokenSource

您应该在有意义的时候CancellationToken进入并检查是否明确要求取消。RunAsync在您的示例中,我可能会在每次迭代中都这样做:

private async Task RunAsync(CancellationToken ct)
{
    PerformanceCounter counter = new PerformanceCounter("Process", "% Processor Time", pServer.ProcessName, true);
    Random r = new Random();
    while (true)
    {
        ct.ThrowIfCancellationRequested();

        float pct = counter.NextValue() / 10f;
        ServerCPU = pct.ToString("0.0");
        await Task.Delay(2000, ct);
    }
}

在来电者网站上,您应该使用CancellationTokenSource. 它将为您提供一种Token传递RunAsync方式以及一种触发取消的方式:

var cts = new CancellationTokenSource();
RunAsync(cts.Token);

// when you want to cancel it the task:
cts.Cancel();

您可以在托管线程中的取消中阅读有关该模式的更多信息。


推荐阅读