假设我有以下Start和Cancel事件处理程序.我如何知道触发取消的人是谁?
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(); }
解决方法
无论是否单击了取消按钮,都存储在字段中:
bool hasUserCancelled = false;
并在开始之前重置此字段:
hasUserCancelled = false; cts = new CancellationTokenSource(); cts.CancelAfter(5000);
在取消按钮单击处理程序中设置它:
private void OnCancelClick(object sender,RoutedEventArgs e) { hasUserCancelled = true; cts.Cancel(); cts.Dispose(); }
您想要的信息现在可以在catch中找到:
catch (TaskCanceledException taskCanceledException) { Debug.WriteLine(new { hasUserCancelled }); }