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();
}
For canceling, we use CancellationTokenSource object.
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 .
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.
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 });
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With