Deadlock while blocking async HttpClient call within a task continuation

若如初见. 提交于 2019-12-07 14:07:11

问题


I am trying to wrap my head around synchronously calling async functions and deadlock.

In the below example I am blocking an async call which internally uses ConfigureAwait(false) which as far as I can tell should prevent deadlock. The first call to the web service does not deadlock. However, the second one that happens within a continuation that syncs back to the UI thread deadlocks.

GetBlocking_Click is a click event in a WPF app so both the first and the second request happen on the UI thread.

      private void GetBlocking_Click(object sender, RoutedEventArgs e)
    {
        const string uri = "http://www.mywebservice.com";
        var example1 = GetAsync(uri).Result;

        Task.FromResult(true)
            .ContinueWith(t =>
            {
                var example2 = GetAsync(uri).Result;
            }, 
            TaskScheduler.FromCurrentSynchronizationContext()).Wait();
    }

    private async Task<string> GetAsync(string url)
    {
        using (var client = new HttpClient())
        {
            var responseMessage = await client.GetAsync(url).ConfigureAwait(false);

            return await responseMessage.Content.ReadAsStringAsync().ConfigureAwait(false);
        }
    }

Can you please explain what is the difference between these 2 calls?


回答1:


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.



来源:https://stackoverflow.com/questions/27825467/deadlock-while-blocking-async-httpclient-call-within-a-task-continuation

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