简体   繁体   English

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

[英]How to use HttpClient without async

Hello I'm following to 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;
}

I use this example on my code and I want to know is there any way to use HttpClient without async/await and how can I get only string of response? 我在我的代码上使用这个例子,我想知道有没有办法在没有async/await情况下使用HttpClient ,我怎样才能得到只有响应的字符串?

Thank you in advance 先感谢您

is there any way to use HttpClient without async/await and how can I get only string of response? 有没有办法在没有async / await的情况下使用HttpClient,我怎样才能得到只有响应的字符串?

HttpClient was specifically designed for asynchronous use. HttpClient专为异步使用而设计。

If you want to synchronously download a string, use WebClient.DownloadString . 如果要同步下载字符串,请使用WebClient.DownloadString

Of course you can: 当然可以:

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

but as @MarcinJuraszek said: 但正如@MarcinJuraszek所说:

"That may cause deadlocks in ASP.NET and WinForms. Using .Result or .Wait() with TPL should be done with caution". “这可能会导致ASP.NET和WinForms出现死锁。使用.Result或.Wait()与TPL应该谨慎”。

Here is the example with WebClient.DownloadString 以下是WebClient.DownloadString的示例

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM