.NET HttpClient parallels API call and throw exception randomly: An existing connection was forcibly closed by the remote host. Error while copying content to a stream.
Remote service: Springboot.
Client environment: .NET Framework 4.8, Console App.
The issue was thrown randomly, but if set
httpClient.DefaultRequestHeaders.ConnectionClose = true;
The issue is gone, but the single call performance goes down, can't leverage the TCP connection. How to solve this issue? it seems like a lib-level bug.
static void Main(string[] args)
{
RunTask().GetAwaiter().GetResult();
}
public async static Task RunTask()
{
HttpClient client = new HttpClient();
for (int j = 0; j < 50; j++)
{
List<Task> tasks = new List<Task>();
for (int i = 0; i < 30; i++)
{
tasks.Add(LoadAsync(client));
}
await Task.WhenAll(tasks);
tasks.ForEach(t => t.GetAwaiter().GetResult());
}
}
public async static Task<string> LoadAsync(HttpClient httpClient)
{
return await httpClient.GetStringAsync(API_URL);
}