2 years ago
#50089
Anton23
Net Core HttpClient is disconnected after 2 minutes
I have a .NET 5 webapi application. Another .NET 5 console application is sending requests to the webapi. I have 10 seconds timeout on each request and I am sending requests one by one with a short interval. On my PC (which is very fast) I send thousands of requests and all of them succeed. But on another PC (which is pretty slow) I get few request failed, approximately every 2 minutes. First request takes a few seconds to send when the application starts because of connection estabishment to webapi.
var httpClient = new HttpClient
{
Timeout = TimeSpan.FromSeconds(10)
};
await PerformPingAsync(httpClient, interval, cts.Token).ConfigureAwait(false);
private static async Task PerformPingAsync(HttpClient httpClient, int interval, CancellationToken cancellationToken)
{
while (!cancellationToken.IsCancellationRequested)
{
try
{
var request = new HttpRequestMessage
{
RequestUri = new Uri("http://127.0.0.1/api/service/ping"),
Method = HttpMethod.Get
};
var response = await httpClient.SendAsync(request, cancellationToken).ConfigureAwait(false);
response.EnsureSuccessStatusCode();
_consoleLogger.Info("Ping attempt succeed");
}
catch (Exception e)
{
_consoleLogger.Error(e);
}
await Task.Delay(TimeSpan.FromSeconds(interval), cancellationToken).ConfigureAwait(false);
}
}
Interval between requests is 1 second. I have tried .net core 3.1, .NET 5 and 6 for my console ping application - and all of them have request timeouts (10 seconds). I have created the same console application in .net framework 4.8 and I get no timeouts. I also created a html page with JS fetch to send request and I get no timeouts. Also what I have discovered that these timeouts can start to happen after a PC reboot. After some of reboots I might not get any timeouts but after the other reboot - I have them.
I found out that HttpClient acts a bit different in .net core/.NET 5/6 than in .net framework. And I tried to use SocketsHttpHandler:
var socketsHandler = new SocketsHttpHandler
{
PooledConnectionLifetime = TimeSpan.FromMinutes(10),
PooledConnectionIdleTimeout = TimeSpan.FromMinutes(10)
};
return new HttpClient(socketsHandler)
{
Timeout = TimeSpan.FromSeconds(10)
};
But I have no success. Due to the official documention PooledConnectionLifetime
timer should be reset after request is sent. If I have no requests for 10 minutes the connection will be closed. It's obvious that my N request is timed out because connection is being reestablished. But why it's happening, why my SocketsHttpHandler
is not working? Any ideas?
asp.net-core
.net-core
timeout
httpclient
0 Answers
Your Answer