You shouldn't be creating HttpClient
instances at random. The client will grab a random port to use and once it has the port that port (because of TCP keep alive) will not be released back anytime soon. Hence when you get to 64K client instantiations (or more likely less) you'll start running into errors.
@AgaveJoe linked to the docs that discuss how to do this properly. For each unique URL domain (not URL within the domain) you can create a separate HttpClient once per app instance. The client is thread safe provided you're not setting default headers. Configure the root client in app startup as part of your DI setup. Then use DI to get the client when you need it. If you need multiple HttpClient
instances pointing to different base URLs then register multiple instances by name so you can select the correct one as needed. Do not dispose of the client when you're done with it.
//App startup
void ConfigureServices ( IServiceCollection services )
{
//If you only need 1 HttpClient then use the simple version
services.AddHttpClient("MyClient")
.ConfigureHttpClient(c => {
c.BaseAddress = new Uri("https://mydomain.com/");
});
//Register services that rely on the named client
services.AddScoped<MyService>(provider => {
var factory = provider.GetRequiredService<IHttpClientFactory();
var client = CreateClient("MyClient");
return new MyService(client);
});
}
//Your code
public class MyService
{
public MyService ( HttpClient client )
{
_client = client;
}
//Your original code
public async Task DoWork ()
{
foreach (var mydata in THE_DATA)
{
client.BaseAddress = new Uri("https://my.domain.com/create.php");
List<MyData> data = null;
using var content = new FormUlrEncodedContent(...);
using (var response = _client.PostAsync("create.php", content))
{
data = await response.Content.ReadFromJsonAsync<List<MyData>();
my_id = data[0].my_id;
};
foreach (var first in mydata.first)
{
using var content = new FormUrlEncodedContent(...);
using (var response = await _client.PostAsync("first.php", content))
{
};
};
...
}
private readonly HttpClient _client;
}