0

.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);
    }
  • 1
    You need to find out why the remote host is closing the connection, or if it is even the remote host (it could be a proxy or firewall in between you and the host). Are you keeping these connections open for a very long time? Often there is a timeout involved. – John Wu Sep 17 '21 at 20:12
  • The connection timeout is the default setting for both the client-side and service side. service keepalive timeout is default 60s. This API call only takes 200ms around. @JohnWu No proxy, or firewall related. it's randomly happened. Disable keepalive works, but performance goes down. – Raymond Peng Sep 17 '21 at 20:18
  • Understood. Again, you have to figure out why the remote host is closing the connection. There is nothing inherently wrong with your code. – John Wu Sep 17 '21 at 20:23
  • Sure, thank you for the reply! – Raymond Peng Sep 17 '21 at 20:40

0 Answers0