How do I know if a job has been canceled by a timeout or manual trigger?

Say that I have the following Start and Cancel event handlers. How to find out who caused 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(); } 
+6
source share
1 answer

Save in the field whether the cancel button is pressed or not:

 bool hasUserCancelled = false; 

And reset this field before running:

  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 you wanted is now available in catch:

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

All Articles