Do HttpClient and HttpClientHandler have to be disposed between requests?

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

    Dispose() calls the code below, which closes the connections opened by the HttpClient instance. The code was created by decompiling with dotPeek.

    HttpClientHandler.cs - Dispose

    ServicePointManager.CloseConnectionGroups(this.connectionGroupName);
    

    If you don't call dispose then ServicePointManager.MaxServicePointIdleTime, which runs by a timer, will close the http connections. The default is 100 seconds.

    ServicePointManager.cs

    internal static readonly TimerThread.Callback s_IdleServicePointTimeoutDelegate = new TimerThread.Callback(ServicePointManager.IdleServicePointTimeoutCallback);
    private static volatile TimerThread.Queue s_ServicePointIdlingQueue = TimerThread.GetOrCreateQueue(100000);
    
    private static void IdleServicePointTimeoutCallback(TimerThread.Timer timer, int timeNoticed, object context)
    {
      ServicePoint servicePoint = (ServicePoint) context;
      if (Logging.On)
        Logging.PrintInfo(Logging.Web, SR.GetString("net_log_closed_idle", (object) "ServicePoint", (object) servicePoint.GetHashCode()));
      lock (ServicePointManager.s_ServicePointTable)
        ServicePointManager.s_ServicePointTable.Remove((object) servicePoint.LookupString);
      servicePoint.ReleaseAllConnectionGroups();
    }
    

    If you haven't set the idle time to infinite then it appears safe not to call dispose and let the idle connection timer kick-in and close the connections for you, although it would be better for you to call dispose in a using statement if you know you are done with an HttpClient instance and free up the resources faster.

提交回复
热议问题