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