runtime: .NET Core 2.1 HttpClient hangs on first SSL call on Mac OS

I stumbled upon this while trying to connect to Microsoft Cognitive Services api in .NET Core 2.1. The first call made using HttpClient hangs and takes about 3-6 seconds. Any calls made on the same HttpClient after this finish at a normal speed (~200ms).

This bug seems to be limited to MacOS/Unix and does NOT affect Windows.

Settings the following switch “solves” the issue, but I suspect something is wrong inside the SocketsHttpHandler for MacOS/Unix.

AppContext.SetSwitch("System.Net.Http.UseSocketsHttpHandler", false);

using System;
using System.Diagnostics;
using System.Net.Http;
using System.Threading.Tasks;

namespace HttpClientTest
{
    public static class Program
    {
        public static async Task Main(string[] args)
        {
            await MakePostCall();
            await MakePostCall();
            await MakePostCall();

            Console.WriteLine("Disable: System.Net.Http.UseSocketsHttpHandler");
            AppContext.SetSwitch("System.Net.Http.UseSocketsHttpHandler", false);

            await MakePostCall();
            await MakePostCall();
            await MakePostCall();

            Console.WriteLine("Done");
        }

        private static async Task MakePostCall()
        {
            var uri = $"http://api.cognitive.microsoft.com/sts/v1.0/issueToken";

            using (var client = new HttpClient())
            {
                var sw = Stopwatch.StartNew();
                await client.PostAsync(uri, new StringContent(""));
                sw.Stop();
                Console.WriteLine($"{sw.ElapsedMilliseconds}ms");
            }
        }
    }
}

Program Output

2396ms
5244ms
5246ms
Disable: System.Net.Http.UseSocketsHttpHandler
270ms
236ms
236ms
Done

About this issue

  • Original URL
  • State: closed
  • Created 6 years ago
  • Comments: 15 (15 by maintainers)

Most upvoted comments

@stephentoub - You are correct, I didn’t notice that number. The DNS seems to be the issue. I forced my computer to point to Google DNS and the issue seems to have resolved.

Additionally, from the original code I posted, they are both running identically.

Thanks for the help

DNS: 52.179.13.227. 00:00:00.0646960.
52.179.13.227. Connected. 00:00:00.2737860
Sent request. 00:00:00.2749880
Received 339 bytes HTTP/1.1 404 Resource Not Found
Content-Length: 54
Content-Type: application/json
apim-request-id: 0a6ab1d0-d76a-45ba-bdb5-9364566ddec8
Strict-Transport-Security: max-age=31536000; includeSubDomains; preload
x-content-type-options: nosniff
Date: Tue, 12 Jun 2018 21:34:03 GMT

{ "statusCode": 404, "message": "Resource not found" }. 00:00:00.5534880
Done
1282ms
1200ms
1227ms
Disable: System.Net.Http.UseSocketsHttpHandler
1246ms
1211ms
1233ms
Done