Deadlock while blocking async HttpClient call within a task continuation

喜欢而已 提交于 2019-12-06 01:21:51

You're in the UI thread. From that thread you call Task.FromResult and create a task. You then add a continuation to that task that needs to run in the UI thread. That continuation is added to the queue for the message pump to handle.

You then wait for that continuation to finish in the UI thread. That continuation is waiting for the UI to be available in order to even start the body of the continuation, which will end up calling GetAsync. This is a deadlock.

It doesn't even matter what the body of the continuation is; the following code deadlocks for the same reason:

private void GetBlocking_Click(object sender, RoutedEventArgs e)
{
    Task.FromResult(true)
        .ContinueWith(t =>{ }, 
            TaskScheduler.FromCurrentSynchronizationContext())
        .Wait();
}

As for the fix, you just shouldn't be synchronously waiting on asynchronous operations in the first place. Either make the whole thing asynchronous, or make it all synchronous.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!