25

I am trying to use Async and Await when making a web request and am finding that it never gets past the await line. I am doing this from a Metro app, but I also verified the problem in a winforms app.

public async Task<string> DoSomething()
{
    string url = "http://imgur.com/gallery/VcBfl.json";
    HttpWebRequest request = HttpWebRequest.CreateHttp(url);

    var ws = await request.GetResponseAsync();

    return ws.ResponseUri.ToString(); ;
}

If I don't use await and instead perform a synchronous wait, it works, but I need this to run asynchronously.

What am I missing in this code that is causing the await to never return?

1 Answer 1

39

I suspect that further up your call stack, you're either calling Wait or Result on the returned Task. This will cause a deadlock, as I describe on my blog.

Follow these best practices to avoid the deadlock:

  1. Don't block on async code; use async all the way down.
  2. In your "library" methods, use ConfigureAwait(false).
Sign up to request clarification or add additional context in comments.

5 Comments

Thank you. That was exactly it. Thanks for the link, it is very helpful.
@Stephen, thanks for the blog posts! Clarifying question: if I use .ConfigureAwait(false) in my lib (basically a WebClient), can I then use .Result when calling it? It seems to work, but I don't know what will happen when I set it loose in the wild.
@Brad: Yes, as long as the async method you're calling does the same thing. However, it's not a best practice to use Result; there are always better options.
@Stephen, the async method I'm calling returns a Task and does NOT call result. The code in question is a custom wrapper for calling an internal API and the only part I want to make async in the actual GET/POST methods (GetRequestStreamAsync, GetResponseAsync, etc). How do I keep this async without making every method between this and the controller action async and returning a Task? I'd like for the lib to take care of the async nature and the consumer to remain agnostic.
@Brad: That's not possible, due to the nature of asynchronous code. It's best to use async all the way.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.