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
.
Author by
Kumar J.
Updated on August 05, 2020Comments
-
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
withoutasync/await
and how can I get only string of response?Thank you in advance
-
MarcinJuraszek over 7 yearsJust FYI: That may cause deadlocks in ASP.NET and WinForms. Using
.Result
or.Wait()
with TPL should be done with caution. -
spender over 7 yearsHah! I just left a comment to this end. The right answer.
-
Kumar J. over 7 yearsThanks but I just following to the guide that I specified in the question
-
Stephen Cleary over 7 years@KumarJ.: Part of following a guide is knowing what needs to be changed.
-
aruno over 6 yearsSee this for info about deadlocking stackoverflow.com/questions/32195595/…
-
Westley Bennett over 2 yearsThis should be marked as the correct answer. Came across this myself.
-
Stephen Cleary over 2 yearsInterestingly, I recently learned (5 years after this answer) that
HttpClient
has a synchronous API as of .NET 5.