我创建了一个简单的 .NET Framework 4.7.2 WPF 应用程序,其中包含两个控件 - 一个文本框和一个按钮。这是我的代码:
private async void StartTest_Click(object sender, RoutedEventArgs e)
{
Output.Clear();
var cancellationTokenSource = new CancellationTokenSource();
// Fire and forget
Task.Run(async () => {
try
{
await Task.Delay(TimeSpan.FromMinutes(1), cancellationTokenSource.Token);
}
catch (OperationCanceledException)
{
Task.Delay(TimeSpan.FromSeconds(3)).Wait();
Print("Task delay has been cancelled.");
}
});
await Task.Delay(TimeSpan.FromSeconds(1));
await Task.Run(() =>
{
Print("Before cancellation.");
cancellationTokenSource.Cancel();
Print("After cancellation.");
});
}
private void Print(string message)
{
var threadId = Thread.CurrentThread.ManagedThreadId;
var time = DateTime.Now.ToString("HH:mm:ss.ffff");
Dispatcher.Invoke(() =>
{
Output.AppendText($"{ time } [{ threadId }] { message }\n");
});
}
按下按钮后,我在文本框中StartTest看到以下结果:Output
12:05:54.1508 [7] Before cancellation.
12:05:57.2431 [7] Task delay has been cancelled.
12:05:57.2440 [7] After cancellation.
我的问题是为什么[7] Task delay has been cancelled.在请求令牌取消的同一线程中执行?
我希望看到的是[7] Before cancellation.然后是[7] After cancellation.然后Task delay has been cancelled.。或者至少Task delay has been cancelled.在另一个线程中执行。
请注意,如果我cancellationTokenSource.Cancel()从主线程执行,那么输出看起来像预期的那样:
12:06:59.5583 [1] Before cancellation.
12:06:59.5603 [1] After cancellation.
12:07:02.5998 [5] Task delay has been cancelled.
Qyouu
相关分类