Async and Await with HttpWebRequest.GetResponseAsync(使用 HttpWebRequest.GetResponseAsync 进行异步和等待)
问题描述
我在发出 Web 请求时尝试使用 Async 和 Await,但我发现它永远不会超过 await 行.我是通过 Metro 应用程序执行此操作的,但我也在 winforms 应用程序中验证了问题.
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(); ;
}
如果我不使用 await 而是执行同步等待,它可以工作,但我需要它异步运行.
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?
推荐答案
我怀疑你的调用堆栈更进一步,你要么在调用 Wait
要么 Result
返回任务
.这将导致死锁,正如我在我的博客中描述的那样.
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:
- 不要阻塞
async
代码;一直使用async
. - 在您的库"方法中,使用
ConfigureAwait(false)
.
- Don't block on
async
code; useasync
all the way down. - In your "library" methods, use
ConfigureAwait(false)
.
这篇关于使用 HttpWebRequest.GetResponseAsync 进行异步和等待的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:使用 HttpWebRequest.GetResponseAsync 进行异步和等待


基础教程推荐
- 经典 Asp 中的 ResolveUrl/Url.Content 等效项 2022-01-01
- JSON.NET 中基于属性的类型解析 2022-01-01
- 在 VS2010 中的 Post Build 事件中将 bin 文件复制到物 2022-01-01
- 首先创建代码,多对多,关联表中的附加字段 2022-01-01
- 将事件 TextChanged 分配给表单中的所有文本框 2022-01-01
- 错误“此流不支持搜索操作"在 C# 中 2022-01-01
- 是否可以在 asp classic 和 asp.net 之间共享会话状态 2022-01-01
- 如何动态获取文本框中datagridview列的总和 2022-01-01
- 从 VS 2017 .NET Core 项目的发布目录中排除文件 2022-01-01
- 全局 ASAX - 获取服务器名称 2022-01-01