It’s dangerous using Wait on a Task and the async keyword together. With applications using the synchronization context(同步上下文), this can easily result in a deadlock.
In the method OnStartDeadlock, the local function DelayAsync is invoked. DelayAsync waits on the completion of Task.Delay before continuing in the foreground thread. However, the caller invokes the Wait
method on the task returned from DelayAsync. The Wait method blocks the calling thread until the task is
completed. In this case, the Wait is invoked from the foreground thread, so the Wait blocks the foreground thread. The await on Task.Delay can never complete, because the foreground thread is not available. This
is a classical deadlock scenario (code file AsyncWindowsApps/MainWindow.xaml.cs):
private void OnStartDeadlock(object sender, RoutedEventArgs e)
{
DelayAsync().Wait();
}
private async Task DelayAsync()
{
await Task.Delay(1000);
}
C# async await 死锁的一个情况
最新推荐文章于 2025-05-08 15:08:08 发布