.NET ServicePoint 对象生命周期

.NET ServicePoint object lifecycle

我一直在设置 ServicePoint.ConnectionLeaseTimeout 属性 当我的网络 API 启动时,以便使用 ServicePointManager.FindServicePoint 定期刷新连接以实现负载平衡。但是,我发现在为 ServicePoint 使用 HTTP 连接后的某个时间,ServicePoint.ConnectionLeaseTimeout 已从我的设置值更改为默认值 -1。 我绝对没有在我的代码中的任何地方将 ServicePoint.ConnectionLeaseTimeout 设置为 -1,而我配置的其他服务点(尚未用于任何连接)仍处于配置值。 因此,我必须假设我最初配置的 ServicePoint 已被处理并替换为新的 ServicePoint 对象,其中 ServicePoint.ConnectionLeaseTimeout 属性 具有默认值。

我知道当超过 ServicePointManager.MaxServicePoints 时可以删除 ServicePoints,但在我的应用程序中 ServicePointManager.MaxServicePoints 设置为 0(无限制)。 我也知道 ServicePoint 可能会在超过 ServicePointManager.MaxServicePointIdleTime 后被处理,但我将其设置为 int.MaxValue (~25 天)并且那个时间肯定没有过去。

有没有人知道如何管理 ServicePoint 的生命周期以及如何更好地管理 ServicePoint 的配置(特别是 ConnectionLeaseTimeout)而无需在应用程序启动时简单地找到 ServicePoint 并设置一次?

The source code for ServicePointManager shows that the ServicePoint objects are wrapped inside WeakReference objects and stored in a Hashtable。 WeakReference 类型提供对对象的引用,同时仍允许该对象被垃圾收集回收。因此,垃圾收集器可能会处理掉 ServicePoint,而 ServicePointManager 随后重新生成了一个新的 ServicePoint 对象来替换它,该对象不会保留 ServicePointManager 无法控制的先前配置值。 似乎没有办法静态配置 ConnectionLeaseTimeout,以便将其应用于新创建的 ServicePoint 对象。

The source code for ServicePointManager shows that TimerThreads are used to remove ServicePoint objects when the connections have been idle for longer than the ServicePointManager.MaxServicePointIdleTime 值。默认值为 100 秒。每个 ServicePoint 将使用创建 ServicePoint 时设置的空闲时间(对 TimerThread.Queue 的引用被传递到 ServicePoint 构造函数),因此更新 ServicePointManager.MaxServicePointIdleTime 不会调整任何现有的 MaxIdleTime ServicePoint 对象,因此请确保在使用任何 HTTP 连接之前对其进行配置。