0

A named HttpClient is registered in Startup.cs as services.AddHttpClient("MainClient").

The HttpClient is used like this in different places:

var httpClient = _httpClientFactory.CreateClient("MainClient");
httpClient.BaseAddress = new Uri(_customUrl);
httpClient.DefaultRequestHeaders.Add("CustomHeader", _customHeader);
var result = await httpClient.SendAsync(...);

The properties _customUrl and _customHeader vary in different places.

Is there a potential race condition when the httpClient is used in different HTTP-requests (or in parallel in multithreading) simultaneously with different BaseAddress and DefaultRequestHeaders?

Is there a way to avoid the race condition? Should lock/semaphoreslim be used in each code parts when httpClient is used?

FireShock
  • 1,082
  • 1
  • 15
  • 25
  • `HttpClient` and `IHttpClientFactory` are both very thread-safe. There are no race-conditions to be concerned about. – Dai May 11 '22 at 11:19
  • 2
    Provided you don't mutate your `HttpClient` instance (i.e. change any of its properties like `DefaultRequestHeaders`) then you'll be fine. However because `HttpClient` instances are mutable they are not really meant to be shared by different parent/owner/containing objects because of the _risk_ of poorly designed code doing something silly like mutating a shared instance. When you use `IHttpClientFactory` then `HttpClient` instances **are super cheap** (due to the factory's inner handler pooling and recycling) so there is no reason to share them. – Dai May 11 '22 at 11:22

0 Answers0