如何使用HttpClient没有async

本文关键字:async 没有 HttpClient 何使用 | 更新日期: 2023-09-27 18:14:35

大家好

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;
}

我在我的代码中使用这个例子,我想知道是否有任何方法可以使用HttpClient而不使用async/await,以及我如何才能只获得响应字符串?

提前感谢

如何使用HttpClient没有async

是否有任何方法使用HttpClient没有async/await,我怎么能得到只有字符串的响应?

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

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

当然可以:

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))
    {
       ...
    }
}