作为一项学习练习,我正在尝试在控制台应用程序中复现在普通 Windows 表单中发生的 async/await 死锁。我希望以下代码会导致这种情况发生,而事实上它确实会发生。但是即使使用 await 时也会出现不可预期的死锁问题。
using System;
using System.Threading;
using System.Threading.Tasks;
using System.Windows.Forms;
static class Program
{
static async Task Main(string[] args)
{
// no deadlocks when this line is commented out (as expected)
SynchronizationContext.SetSynchronizationContext(new WindowsFormsSynchronizationContext());
Console.WriteLine("before");
//DoAsync().Wait(); // deadlock expected...and occurs
await DoAsync(); // deadlock not expected...but also occurs???
Console.WriteLine("after");
}
static async Task DoAsync()
{
await Task.Delay(100);
}
}
我主要是想知道为什么会发生这种情况?
WinformsApartment
代码感兴趣。 - noseratio - open to work