如何知道Task是由超时还是手动触发取消的?

本文关键字:取消 Task 何知道 超时 | 更新日期: 2023-09-27 17:51:22

假设我有以下Start和Cancel事件处理程序。我怎么知道是谁取消了预约?

private CancellationTokenSource cts;
    private async void OnStartClick(object sender, RoutedEventArgs e)
    {
        try
        {
            cts = new CancellationTokenSource();
            cts.CancelAfter(5000);
            await Task.Delay(10000,cts.Token);
        }
        catch (TaskCanceledException taskCanceledException)
        {
            ??? How do i know who canceled the task here ???
        }
    }
    private void OnCancelClick(object sender, RoutedEventArgs e)
    {
        cts.Cancel();
        cts.Dispose();
    }

如何知道Task是由超时还是手动触发取消的?

在字段中存储取消按钮是否被单击:

bool hasUserCancelled = false;

并在开始前重置此字段:

        hasUserCancelled = false;
        cts = new CancellationTokenSource();
        cts.CancelAfter(5000);

在取消按钮点击处理程序中设置:

private void OnCancelClick(object sender, RoutedEventArgs e)
{
    hasUserCancelled = true;
    cts.Cancel();
    cts.Dispose();
}

你想要的信息现在可以在catch语句中找到了:

    catch (TaskCanceledException taskCanceledException)
    {
        Debug.WriteLine(new { hasUserCancelled });
    }