What is the best way to use HttpClient
and avoid deadlock? I am using the code below, called entirely from synchronous methods, but I concerned it maybe causing
In my case, when I used await client.GetAsync()
, I didnot receive any response, when I tried to observe the problem, the debugger also terminated on the above GetAsync() line. I could only use client.GetAsync().Result
to get the reponse correctly, but I saw many saying that it may lead to deadlock like in this post and it is synchronous too. I was particularly using this in UI button click event as well, which is not recommended.
Finally, I got it working by adding the below three lines, I didnot have those three lines before (maybe that was the problem):
using (var client = new HttpClient())
{
string relativeURL = "api/blah";
//These three lines - BaseAddress, DefaultRequestHeaders and DefaultRequestHeaders
client.BaseAddress = new Uri(Constants.ServiceBaseAddress);
client.DefaultRequestHeaders.Clear();
client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
HttpResponseMessage response = await client.GetAsync(relativeURL);
...
}
NOTE:
Constants.ServiceBaseAddress
is https://domainname.org/
This is working fine now, with async signature and no deadlock worries. Hope this helps somebody.