0

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

3
  • Why would HttpClient be thread safe, that's your responsibility. You shall not use static object in the rest API. Also true Async calls are not made on the thread, they use IO completion ports Commented Oct 6, 2018 at 8:20
  • 1
    Because the documentation at Microsoft says so and that the correvt implementation of HttpClient is to use a static object? learn.microsoft.com/en-us/dotnet/api/… Commented Oct 6, 2018 at 9:05
  • Or am I missing something here? Commented Oct 6, 2018 at 9:06

1 Answer 1

1

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.

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.