How to use HttpClient without async

大城市里の小女人 提交于 2020-02-27 22:22:12

问题


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?

Thank you in advance


回答1:


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:

"That may cause deadlocks in ASP.NET and WinForms. Using .Result or .Wait() with TPL should be done with caution".

Here is the example with WebClient.DownloadString

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



回答2:


is there any way to use HttpClient without async/await and how can I get only string of response?

HttpClient was specifically designed for asynchronous use.

If you want to synchronously download a string, use WebClient.DownloadString.



来源:https://stackoverflow.com/questions/40208647/how-to-use-httpclient-without-async

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!