I've noticed that using HttpClient is NOT thread safe when modifying HttpClient.DefaultRequestHeaders but I want to make as many requests as possible. I need a custom header each request (2 other headers are always the same). Also the URL changes a bit
Currently I'm creating a new HttpClient for every request but I feel like creating 10k+ HttpClients isn't the best choice here.
I'd like to make one static HttpClient with 2 DefaultRequestHeaders and use this HttpClient for every request but also add one custom header.
I want to make this as fast as possible so if you have something else I'll take it.
Parallel.ForEach(Requests, Request =>
{
var Client = new HttpClient();
Client.DefaultRequestHeaders.Clear();
Client.DefaultRequestHeaders.Add("Header1", "Value1");
Client.DefaultRequestHeaders.Add("Header2", "Value2");
Client.DefaultRequestHeaders.Add("Header3", "Value for exact this request");
var response = Client.PutAsync(new Uri($"http://example.com/books/1234/readers/837"), null); //.Result (?)
Client.Dispose();
});
Don’t use DefaultRequestHeaders for headers that don’t apply to all requests the HttpClient sends.
Also, don’t create an HttpClient per request.
You can do this easily by instead creating one HttpRequestMessage for each request, applying whatever headers you need to it, and using the same HttpClient throughout to .SendAsync() them:
using (var request = new HttpRequestMessage(HttpMethod.Put, url)
{
request.Headers.<add here>;
// optionally set .Content
using (var response = await httpClient.SendAsync(request))
{
// ... process response
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With