3

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?

Alex K
  • 33
  • 5
  • 3
    Don't synchronously block on asynchronous methods. Period. It's virtually always the wrong thing to be doing. `await` the method in the click handler instead. – Servy Jan 07 '15 at 17:50

1 Answers1

5

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.

Servy
  • 202,030
  • 26
  • 332
  • 449
  • actually this continuation does run. It is the GetAsync within the continuation that deadlocks. The behaviour that you describe is valid if I actually start a task via `Task.Run`, for example `Task.Run(() => true)`, in which case another thread pool thread returns true. However, in the example where `Task.FromResult` is used the continuation is run but GetAsync deadlocks. I agree with async all the way but I am just trying to understand why the first example works and the second doesn't. – Alex K Jan 08 '15 at 09:03
  • @AlexK No, that's not true. You pass the current context into the `ContinueWith` call, so while the continuation will be *scheduled* immediately, it won't actually start executing until the synchronization context actually executes the method. It won't be able to execute the method until the current message it's pumping, the click event handler, completes. As I said, `GetAsync` is not involved at all in the deadlock. – Servy Jan 08 '15 at 15:11
  • as far as I can see from debugging it on a WPF application it is true. The first code snippet using `Task.FromResult(true)` breaks on `var example2 = GetAsync(uri).Result` and then deadlocks. if I replace `Task.FromResult(true)` with `Task.Run(() => true)` then the application deadlocks without reaching the continuation. Could you please explain the difference between these 2 pieces of code? I am accepting your answer anyway because you are pointing me to the right direction. Thanks – Alex K Jan 08 '15 at 15:47