Avoiding Deadlock with HttpClient

后端 未结 3 1555
失恋的感觉
失恋的感觉 2021-01-03 10:57

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

3条回答
  •  -上瘾入骨i
    2021-01-03 11:20

    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;
        }
    }
    

提交回复
热议问题