简体   繁体   中英

HttpClient multithreading with Content.ReadAsAsync method

Iv been reading alot about HttpClient and realized that I had to change our implementation of our RestHandler due to we were instantiating a new HttpClient object for each request. We use alot of request for our RestHandler (using HttpClient).

Questions:

  • Iv read that several (all?) methods on HttpClient is thread safe, does that mean that my code below will not have any problems with threading all though Im using the Content.ReadAsAsync?
  • Are there any other known issues in using HttpClient in this way?

Now the implementation looks something like this:

public class RestHandler : IRestHandler
{
    private static readonly HttpClient HttpClient = new HttpClient();

    public RestHandler()
    {
        //HttpClient.DefaultRequestHEaders.Authorization = new AuthenticationHeaderValue(some logic);
        //HttpClient.DefaultRequestHEaders.Add("id","customId");
    }

    public async Task<GenericResult<T>> GetResultAsync<T>(string url) where T : new()
    { 
        var response = await HttpClient.GetAsync(url);

        var result = await response.Content.ReadAsAsync<T>();

        return new GenericResult<T> { HttpResponseMessage = response, Result = result};
    }
}

public interface IRestHandler
{ 
    Task<GenericResult<T>> GetResultAsync<T>(string url) where T : new();
}

public class GenericResult<T> where T : new()
{
    public T Result { get; set; }
    public HttpResponseMessage HttpResponseMessage { get; set; }
}

Best regards Robert

Read this: You're using httpClient wrong and it's destabilizing your software

It talks about how HttpClient is truly reentrant and thread-safe. It also proves its case for why you should be using one single HttpClient for the entire application.

What you're doing looks fine to me.

As an aside, I've personally had problems with HttpClient and Mono. We use RestSharp and prefer it.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM