C# で new HttpClient() をリクエストごとに new / Dispose すると、しばらくして ソケット枯渇・断続的タイムアウト・SocketException が出ることがある。
この記事ではなぜ起きるかといまの定石(IHttpClientFactory)をざっくり整理する。
new HttpClient() しないIHttpClientFactory(AddHttpClient)を使うHttpClient を Dispose しても、裏の接続がすぐ OS に返るとは限らない// NG: 都度 new
using var client = new HttpClient();
await client.GetAsync(url);
// OK: Factory(型指定クライアント例)
builder.Services.AddHttpClient<IGitHubClient, GitHubClient>(c =>
{
c.BaseAddress = new Uri("https://api.github.com/");
c.Timeout = TimeSpan.FromSeconds(30);
});
public class GitHubClient(HttpClient http) : IGitHubClient
{
public Task<string> GetAsync(string path)
=> http.GetStringAsync(path);
}
名前付きクライアントでも可: AddHttpClient("payments") → factory.CreateClient("payments")。
「アプリで 1 個を使い回せ」も昔の助言。ただし DNS 更新が反映されにくいなどの理由で、今は IHttpClientFactory 推奨。
new HttpClient( が散らばっていないか検索SocketException / HttpRequestException / タイムアウト