Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
588 views
in Technique[技术] by (71.8m points)

c# - Async and Await with HttpWebRequest.GetResponseAsync

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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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).

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...