C# 使用 HttpWebRequest.GetResponseAsync 异步和等待
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/12701545/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Async and Await with HttpWebRequest.GetResponseAsync
提问by John Koerner
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.
我在发出 Web 请求时尝试使用 Async 和 Await,但我发现它永远不会超过 await 线。我是通过 Metro 应用程序执行此操作的,但我也在 winforms 应用程序中验证了该问题。
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.
如果我不使用 await 而是执行同步等待,它可以工作,但我需要它异步运行。
What am I missing in this code that is causing the await to never return?
我在这段代码中遗漏了什么导致等待永远不会返回?
采纳答案by Stephen Cleary
I suspect that further up your call stack, you're either calling Waitor Resulton the returned Task. This will cause a deadlock, as I describe on my blog.
我怀疑在你的调用堆栈上,你要么调用Wait要么Result在返回的Task. 这将导致僵局,正如我在我的博客中所描述的。
Follow these best practices to avoid the deadlock:
请遵循以下最佳实践来避免死锁:
- Don't block on
asynccode; useasyncall the way down. - In your "library" methods, use
ConfigureAwait(false).
- 不要阻塞
async代码;一直使用async下去。 - 在您的“库”方法中,使用
ConfigureAwait(false).

