如何在没有异步的情况下使用HttpClient

Kum*_* J. 7 c# asp.net asp.net-mvc webclient

您好我正在关注本指南

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;
}
Run Code Online (Sandbox Code Playgroud)

我用这个例子在我的代码,我想知道有没有办法使用HttpClient没有async/await,我怎么能得到的唯一反应的字符串?

先感谢您

Ste*_*ary 20

有没有办法在没有async/await的情况下使用HttpClient,我怎样才能得到只有响应的字符串?

HttpClient 是专为异步使用而设计的.

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

  • @KumarJ.:遵循指南的一部分是了解需要改变的内容. (4认同)
  • 有趣的是,我最近了解到(在这个答案 5 年后)[`HttpClient` 自 .NET 5 起有一个同步 API](https://learn.microsoft.com/en-us/dotnet/api/system.net。 http.httpclient.send?view=net-5.0)。 (3认同)
  • 哈!我刚刚为此发表评论.正确的答案. (2认同)

Rom*_*syk 15

当然可以:

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();
        }
    }
 }
Run Code Online (Sandbox Code Playgroud)

但正如@MarcinJuraszek 所说:

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

这是一个例子WebClient.DownloadString

using (var client = new WebClient())
{
    string response = client.DownloadString(path);
    if (!string.IsNullOrEmpty(response))
    {
       ...
    }
}
Run Code Online (Sandbox Code Playgroud)

  • 仅供参考:这可能会导致 ASP.NET 和 WinForms 中出现死锁。应谨慎使用“.Result”或“.Wait()”与 TPL。 (6认同)
  • 有关死锁的信息,请参阅此 /sf/ask/2253691681/ (2认同)