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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-10 00:09:32  来源:igfitidea点击:

Async and Await with HttpWebRequest.GetResponseAsync

c#windows-8windows-runtimehttpwebrequestasync-await

提问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:

请遵循以下最佳实践来避免死锁:

  1. Don't block on asynccode; use asyncall the way down.
  2. In your "library" methods, use ConfigureAwait(false).
  1. 不要阻塞async代码;一直使用async下去。
  2. 在您的“库”方法中,使用ConfigureAwait(false).