We are creating a wrapper for the HttpClient. As we will follow performance optimization recommendations from https://github.com/mspnp/performance-optimization . We want to avoid the anti-template - the wrong instance mentioned in this document. I passed this guide to my team in order to use the static HttpClient. The feedback I received is regarding thread safety. Each request has a header containing the user's request. Since I have a static HttpClient, will it be thread safe? If we have several requests hitting the code (for example, GET) at the same time, will the race condition set the title? We have an implementation as shown below.
public class HttpClientHelper{ private static readonly HttpClient _HttpClient; static HttpClientHelper() { HttpClient = new HttpClient(); HttpClient.Timeout = TimeSpan.FromMinutes(SOME_CONFIG_VALUE); } public async Task<HttpResponseMessage> CallHttpClientPostAsync(string requestUri, HttpContent requestBody) { AddHttpRequestHeader(httpClient); var response = await httpClient.PostAsync(requestUri, requestBody);
}
sadhat75
source share