Do HttpClient and HttpClientHandler have to be disposed between requests?

前端 未结 12 2173
鱼传尺愫
鱼传尺愫 2020-11-22 02:06

System.Net.Http.HttpClient and System.Net.Http.HttpClientHandler in .NET Framework 4.5 implement IDisposable (via System.Net.Http.HttpMessageInvoker).

The usin

12条回答
  •  独厮守ぢ
    2020-11-22 02:29

    I think one should use singleton pattern to avoid having to create instances of the HttpClient and closing it all the time. If you are using .Net 4.0 you could use a sample code as below. for more information on singleton pattern check here.

    class HttpClientSingletonWrapper : HttpClient
    {
        private static readonly Lazy Lazy= new Lazy(()=>new HttpClientSingletonWrapper()); 
    
        public static HttpClientSingletonWrapper Instance {get { return Lazy.Value; }}
    
        private HttpClientSingletonWrapper()
        {
        }
    }
    

    Use the code as below.

    var client = HttpClientSingletonWrapper.Instance;
    

提交回复
热议问题