How to use HttpClient without async

27,443

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

Solution 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.

Share:
27,443
Kumar J.
Author by

Kumar J.

Updated on August 05, 2020

Comments

  • Kumar J.
    Kumar J. almost 4 years

    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

  • MarcinJuraszek
    MarcinJuraszek over 7 years
    Just FYI: That may cause deadlocks in ASP.NET and WinForms. Using .Result or .Wait() with TPL should be done with caution.
  • spender
    spender over 7 years
    Hah! I just left a comment to this end. The right answer.
  • Kumar J.
    Kumar J. over 7 years
    Thanks but I just following to the guide that I specified in the question
  • Stephen Cleary
    Stephen Cleary over 7 years
    @KumarJ.: Part of following a guide is knowing what needs to be changed.
  • aruno
    aruno over 6 years
    See this for info about deadlocking stackoverflow.com/questions/32195595/…
  • Westley Bennett
    Westley Bennett over 2 years
    This should be marked as the correct answer. Came across this myself.
  • Stephen Cleary
    Stephen Cleary over 2 years
    Interestingly, I recently learned (5 years after this answer) that HttpClient has a synchronous API as of .NET 5.