많은 개발자가 매 요청마다 새로운 HttpClient 인스턴스를 생성합니다. 하지만 이는 각 인스턴스가 시스템 소켓을 소모하여 소켓 고갈 및 성능 저하를 초래하기 때문에 바람직하지 않습니다.
public async Task<string> GetDataAsync(string url)
{
using (var client = new HttpClient()) // ❌ Bad: New client per request
{
return await client.GetStringAsync(url);
}
}
대신, 여러 요청에 걸쳐 단일 HttpClient 인스턴스를 재사용하는 것이 좋습니다. 이렇게 하면 과도한 소켓 사용량을 방지할 수 있습니다.
private static readonly HttpClient _httpClient = new HttpClient();
public async Task<string> GetDataAsync(string url)
{
return await _httpClient.GetStringAsync(url);
}
// Allow 1 second to process queued msgs before closing the socket.
LingerOption lingerOption = new LingerOption (true, 1);
tcpClient.LingerState = lingerOption;
tcpClient.Close();
// Close the socket right away without lingering.
LingerOption lingerOption = new LingerOption (true, 0);
tcpClient.LingerState = lingerOption;
tcpClient.Close();