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-06-14 08:57:25 发布
本文详细探讨了C#中使用async await时可能出现的死锁现象,通过一个具体的示例展示了当异步操作与同步上下文交织时如何导致线程阻塞。了解这种死锁情况对于避免在多线程编程中出现意外的系统挂起至关重要。
723

被折叠的 条评论
为什么被折叠?



