异步和等待与HttpWebRequest

异步和等待与HttpWebRequest

本文介绍了异步和等待与HttpWebRequest.GetResponseAsync的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想提出一个web请求时使用异步和等待和我发现,它一直无法完成的await线。我从地铁应用程序这样做,但我在一个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.

我是什么在这个code就是造成的await永不返回不见了?

What am I missing in this code that is causing the await to never return?

推荐答案

我怀疑进一步您的调用堆栈,你要么调用等待结果对返回工作这将导致死锁,因为我描述我的博客

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. 请不要在阻止异步 code;使用异步一路下滑。

  2. 在库的方法,用 ConfigureAwait(假)

  1. Don't block on async code; use async all the way down.
  2. In your "library" methods, use ConfigureAwait(false).

这篇关于异步和等待与HttpWebRequest.GetResponseAsync的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!