Share via


HttpClientBuilderExtensions.SetHandlerLifetime Method

Definition

Sets the length of time that a HttpMessageHandler instance can be reused. Each named client can have its own configured handler lifetime value. The default value is two minutes. Set the lifetime to InfiniteTimeSpan to disable handler expiry.

public:
[System::Runtime::CompilerServices::Extension]
 static Microsoft::Extensions::DependencyInjection::IHttpClientBuilder ^ SetHandlerLifetime(Microsoft::Extensions::DependencyInjection::IHttpClientBuilder ^ builder, TimeSpan handlerLifetime);
public static Microsoft.Extensions.DependencyInjection.IHttpClientBuilder SetHandlerLifetime (this Microsoft.Extensions.DependencyInjection.IHttpClientBuilder builder, TimeSpan handlerLifetime);
static member SetHandlerLifetime : Microsoft.Extensions.DependencyInjection.IHttpClientBuilder * TimeSpan -> Microsoft.Extensions.DependencyInjection.IHttpClientBuilder
<Extension()>
Public Function SetHandlerLifetime (builder As IHttpClientBuilder, handlerLifetime As TimeSpan) As IHttpClientBuilder

Parameters

handlerLifetime
TimeSpan

Returns

Remarks

The default implementation of IHttpClientFactory will pool the HttpMessageHandler instances created by the factory to reduce resource consumption. This setting configures the amount of time a handler can be pooled before it is scheduled for removal from the pool and disposal.

Pooling of handlers is desirable as each handler typically manages its own underlying HTTP connections; creating more handlers than necessary can result in connection delays. Some handlers also keep connections open indefinitely which can prevent the handler from reacting to DNS changes. The value of handlerLifetime should be chosen with an understanding of the application's requirement to respond to changes in the network environment.

Expiry of a handler will not immediately dispose the handler. An expired handler is placed in a separate pool which is processed at intervals to dispose handlers only when they become unreachable. Using long-lived HttpClient instances will prevent the underlying HttpMessageHandler from being disposed until all references are garbage-collected.

Applies to