HttpClientHandler / HttpClient Memory Leak

后端 未结 4 1429
逝去的感伤
逝去的感伤 2020-12-03 01:24

I have anywhere from 10-150 long living class objects that call methods performing simple HTTPS API calls using HttpClient. Example of a PUT call:



        
4条回答
  •  孤城傲影
    2020-12-03 02:10

    Using the repro form Alexandr Nikitin, I was able to discover that this seems to happen ONLY when you have HttpClient be a short lived object. If you make the handler and client long lived this does not seem to happen:

    using System;
    using System.Net.Http;
    using System.Threading.Tasks;
    
    namespace HttpClientMemoryLeak
    {
        using System.Net;
        using System.Threading;
    
        class Program
        {
            static HttpClientHandler handler = new HttpClientHandler();
    
            private static HttpClient client = new HttpClient(handler);
    
            public static async Task TestMethod()
            {
                try
                {
                    using (var response = await client.PutAsync("http://localhost/any/url", null))
                    {
                    }
                }
                catch
                {
                }
            }
    
            static void Main(string[] args)
            {
                for (int i = 0; i < 1000000; i++)
                {
                    Thread.Sleep(10);
                    TestMethod();
                }
    
                Console.WriteLine("Finished!");
                Console.ReadKey();
            }
        }
    }
    

提交回复
热议问题