Search code examples
c#task-parallel-libraryasync-awaitcancellationtokensource

How do I know whether a Task is canceled by a timeout or a manual trigger?


Say I have the following Start and Cancel event handlers. How do I know who was the one who triggered the cancellation?

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

Solution

  • Store in a field whether the cancel-button was clicked or not:

    bool hasUserCancelled = false;
    

    And reset this field before you start:

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

    Set it in the cancel-button click handler:

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

    The information that you wanted is now available in the catch:

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