call async method without await #2

Catalin picture Catalin · Nov 5, 2013 · Viewed 68.3k times · Source

I have an async method:

public async Task<bool> ValidateRequestAsync(string userName, string password)
{
    using (HttpClient client = new HttpClient())
    {
        HttpResponseMessage response = await client.GetAsync(url);
        string stringResponse = await response.Content.ReadAsStringAsync();

        return bool.Parse(stringResponse);
    }
}

I call this method like this:

bool isValid = await ValidateRequestAsync("user1", "pass1");

Can i call the same method from an synchronous method, without using await keyword?

Ex:

public bool ValidateRequest(string userName, string password)
{
    return ValidateRequestAsync(userName, password).Result;
}

I think this will cause a deadlock.

EDIT

Calling the method like above makes the call never end. (The method doesn't reaches the end anymore)

Answer

Kris Vandermotten picture Kris Vandermotten · Nov 5, 2013

If you call an async method from a single threaded execution context, such as a UI thread, and wait for the result synchronously, there is a high probability for deadlock. In your example, that probability is 100%

Think about it. What happens when you call

ValidateRequestAsync(userName, password).Result

You call the method ValidateRequestAsync. In there you call ReadAsStringAsync. The result is that a task will be returned to the UI thread, with a continuation scheduled to continue executing on the UI thread when it becomes available. But of course, it will never become available, because it is waiting (blocked) for the task to finish. But the task can't finish, because it is waiting for the UI thread to become available. Deadlock.

There are ways to prevent this deadlock, but they are all a Bad Idea. Just for completeness sake, the following might work:

Task.Run(async () => await ValidateRequestAsync(userName, password)).Result;

This is a bad idea, because you still block your UI thread waiting and doing nothing useful.

So what is the solution then? Go async all the way. The original caller on the UI thread is probably some event handler, so make sure that is async.