使用 HttpWebRequest.GetResponseAsync 进行异步和等待

编程入门 行业动态 更新时间:2024-10-18 23:23:05
本文介绍了使用 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 = "imgur/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; use async all the way down.
  • In your "library" methods, use ConfigureAwait(false).
  • 更多推荐

    使用 HttpWebRequest.GetResponseAsync 进行异步和等待

    本文发布于:2023-11-13 00:35:01,感谢您对本站的认可!
    本文链接:https://www.elefans.com/category/jswz/34/1582921.html
    版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
    本文标签:HttpWebRequest   GetResponseAsync

    发布评论

    评论列表 (有 0 条评论)
    草根站长

    >www.elefans.com

    编程频道|电子爱好者 - 技术资讯及电子产品介绍!