Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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();
    }
like image 729
icube Avatar asked Mar 22 '14 10:03

icube


People also ask

Which object do you inspect to determine if a long running task will be Cancelled?

For canceling, we use CancellationTokenSource object.

What is task Cancelled exception?

There's 2 likely reasons that a TaskCanceledException would be thrown: Something called Cancel() on the CancellationTokenSource associated with the cancellation token before the task completed. The request timed out, i.e. didn't complete within the timespan you specified on HttpClient. Timeout .

Which method can you use to cancel an ongoing operation that uses CancellationToken?

The CancellationToken is used in asynchronous task. The CancellationTokenSource token is used to signal that the Task should cancel itself. In the above case, the operation will just end when cancellation is requested via Cancel() method.


1 Answers

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 });
    }
like image 173
usr Avatar answered Oct 31 '22 22:10

usr