【问题标题】:How to use HttpClient without async如何在没有异步的情况下使用 HttpClient
【发布时间】:2017-03-05 15:41:48
【问题描述】:

大家好,我关注this guide

static async Task<Product> GetProductAsync(string path)
{
    Product product = null;
    HttpResponseMessage response = await client.GetAsync(path);
    if (response.IsSuccessStatusCode)
    {
        product = await response.Content.ReadAsAsync<Product>();
    }
    return product;
}

我在我的代码中使用了这个例子,我想知道有没有什么方法可以在没有async/await 的情况下使用HttpClient,我怎样才能只得到响应字符串?

提前谢谢你

【问题讨论】:

标签: c# asp.net asp.net-mvc webclient


【解决方案1】:

当然可以:

public static string Method(string path)
{
   using (var client = new HttpClient())
   {
       var response = client.GetAsync(path).GetAwaiter().GetResult();
       if (response.IsSuccessStatusCode)
       {
            var responseContent = response.Content;
            return responseContent.ReadAsStringAsync().GetAwaiter().GetResult();
        }
    }
 }

但正如@MarcinJuraszek 所说:

"这可能会导致 ASP.NET 和 WinForms 中的死锁。使用 .Result 或 .Wait() 与 TPL 应谨慎执行”。

这里是WebClient.DownloadString的例子

using (var client = new WebClient())
{
    string response = client.DownloadString(path);
    if (!string.IsNullOrEmpty(response))
    {
       ...
    }
}

【讨论】:

【解决方案2】:

有什么方法可以在没有 async/await 的情况下使用 HttpClient,我怎样才能只获得响应字符串?

HttpClient 专为异步使用而设计。

如果要同步下载字符串,请使用WebClient.DownloadString

【讨论】:

  • 哈!我只是为此发表了评论。正确答案。
  • 谢谢,但我只是按照我在问题中指定的指南进行操作
  • @KumarJ.:遵循指南的一部分是了解需要更改的内容。
  • 这应该被标记为正确答案。我自己也遇到过。
  • 有趣的是,我最近了解到(在此答案后 5 年)HttpClient has a synchronous API as of .NET 5
猜你喜欢
  • 2019-12-16
  • 1970-01-01
  • 1970-01-01
  • 2013-07-22
  • 2012-11-15
  • 2020-08-22
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多