如何知道超时或手动触发器是否取消了任务?

时间:2014-03-22 10:21:04

标签: c# task-parallel-library async-await cancellationtokensource

假设我有以下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();
    }

1 个答案:

答案 0 :(得分:8)

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

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 });
    }