Do HttpClient and HttpClientHandler have to be disposed between requests?

前端 未结 12 1976
鱼传尺愫
鱼传尺愫 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:26

    In my case, I was creating an HttpClient inside a method that actually did the service call. Something like:

    public void DoServiceCall() {
      var client = new HttpClient();
      await client.PostAsync();
    }
    

    In an Azure worker role, after repeatedly calling this method (without disposing the HttpClient), it would eventually fail with SocketException (connection attempt failed).

    I made the HttpClient an instance variable (disposing it at the class level) and the issue went away. So I would say, yes, dispose the HttpClient, assuming its safe (you don't have outstanding async calls) to do so.

提交回复
热议问题