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
I think you mean avoid blocking. Deadlocks refer to situations where two or more threads are all indefinitely waiting for each other to finish.
To avoid blocking in your sample code, instead of synchronously waiting on Results, you just need to await
the non-blocking API calls:
HttpContent content = new StringContent(json, Encoding.UTF8, "application/json");
using (HttpClient client = new HttpClient())
{
HttpResponseMessage responseMessage = null;
switch (verb)
{
case HttpVerb.Put:
responseMessage = await client.PutAsync(url, content);
break;
case HttpVerb.Post:
responseMessage = await client.PostAsync(url, content);
break;
case HttpVerb.Delete:
responseMessage = await client.DeleteAsync(url);
break;
case HttpVerb.Get:
responseMessage = await client.GetAsync(url);
break;
}
if (responseMessage.IsSuccessStatusCode)
{
responseContent = await responseMessage.Content.ReadAsStringAsync();
statusCode = responseMessage.StatusCode;
}
}