Skip to content

.NET Core 2.1 HttpClient hangs on first SSL call on Mac OS  #26427

@razfriman

Description

@razfriman

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

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    No projects

    Milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions