What is the overhead of creating a new HttpClient per call in a WebAPI client?

前端 未结 7 1952
心在旅途
心在旅途 2020-11-22 07:26

What should be the HttpClient lifetime of a WebAPI client?
Is it better to have one instance of the HttpClient for multiple calls?

Wh

7条回答
  •  栀梦
    栀梦 (楼主)
    2020-11-22 07:48

    Related to high-volume web sites but not directly to HttpClient. We have the snippet of code below in all of our services.

            // number of milliseconds after which an active System.Net.ServicePoint connection is closed.
            const int DefaultConnectionLeaseTimeout = 60000;
    
            ServicePoint sp =
                    ServicePointManager.FindServicePoint(new Uri("http://"));
            sp.ConnectionLeaseTimeout = DefaultConnectionLeaseTimeout;
    

    From https://msdn.microsoft.com/query/dev14.query?appId=Dev14IDEF1&l=EN-US&k=k(System.Net.ServicePoint.ConnectionLeaseTimeout);k(TargetFrameworkMoniker-.NETFramework,Version%3Dv4.5.2);k(DevLang-csharp)&rd=true

    "You can use this property to ensure that a ServicePoint object's active connections do not remain open indefinitely. This property is intended for scenarios where connections should be dropped and reestablished periodically, such as load balancing scenarios.

    By default, when KeepAlive is true for a request, the MaxIdleTime property sets the time-out for closing ServicePoint connections due to inactivity. If the ServicePoint has active connections, MaxIdleTime has no effect and the connections remain open indefinitely.

    When the ConnectionLeaseTimeout property is set to a value other than -1, and after the specified time elapses, an active ServicePoint connection is closed after servicing a request by setting KeepAlive to false in that request. Setting this value affects all connections managed by the ServicePoint object."

    When you have services behind a CDN or other endpoint that you want to failover then this setting helps callers follow you to your new destination. In this example 60 seconds after a failover all callers should re-connect to the new endpoint. It does require that you know your dependent services (those services that YOU call) and their endpoints.

提交回复
热议问题