You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

已过时FindServicePoint方法的升级路径及ConnectionLeaseTimeout替代方案

如何用HttpClient替代ServicePointManager的ConnectionLeaseTimeout?

在SocketsHttpHandler中,**PooledConnectionLifetime**属性就是原ConnectionLeaseTimeout的直接替代,它的作用和后者完全一致:限制连接池中单个连接的最长存活时间,到期后连接会被标记为过期,不再被后续请求复用。

代码示例

// 配置SocketsHttpHandler,设置连接生命周期为1分钟(对应原代码的60*1000毫秒)
var handler = new SocketsHttpHandler
{
    PooledConnectionLifetime = TimeSpan.FromMinutes(1),
    // 可选:设置连接空闲超时(空闲多久后被回收)
    PooledConnectionIdleTimeout = TimeSpan.FromMinutes(2)
};

// 复用该HttpClient实例(不要每次请求都新建)
var httpClient = new HttpClient(handler);

// 使用HttpClient发送请求
var response = await httpClient.GetAsync(myServiceUrl);

关键说明

  • PooledConnectionLifetime:强制控制连接的最大存活时长,无论连接是否处于空闲状态,到期就会从连接池中移除,解决原ConnectionLeaseTimeout要处理的“长期持有旧连接导致DNS更新不生效”等问题;
  • PooledConnectionIdleTimeout:可选配置,用于设置连接空闲状态下的最长存活时间,和PooledConnectionLifetime配合使用可以更精细化管理连接池;
  • 务必复用HttpClient实例,频繁创建销毁HttpClient会导致连接池混乱,这是使用HttpClient的核心最佳实践。

内容的提问来源于stack exchange,提问作者Matthew MacFarland

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.07 23:40:40