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