.NET ServicePoint object lifecycle

1.2k views Asked by At

I have been setting the ServicePoint.ConnectionLeaseTimeout property when my web API starts up so that connections are refreshed regularly for load balancing scenarios by using ServicePointManager.FindServicePoint. But, I am finding that at some time after using HTTP connections for the ServicePoint the ServicePoint.ConnectionLeaseTimeout has changed from my set value to the default -1. I am definitely not setting the ServicePoint.ConnectionLeaseTimeout to -1 anywhere in my code and the other service points that I have configured, which have not been used for any connections are still at the configured value. So, I must assume that the ServicePoint that I originally configured has been disposed of and replaced with a new ServicePoint object where the ServicePoint.ConnectionLeaseTimeout property has the default value.

I know that ServicePoints can be deleted when ServicePointManager.MaxServicePoints is exceeded, but in my application ServicePointManager.MaxServicePoints is set to 0 (unlimited). I'm also aware that the ServicePoint may be disposed after ServicePointManager.MaxServicePointIdleTime is exceeded, but I am setting it to int.MaxValue (~25 days) and that time has definitely not passed.

Does anyone have any other information on how the lifecycle of ServicePoint is managed and how to better manage the configuration of a ServicePoint (in particular ConnectionLeaseTimeout) without simply finding the ServicePoint at application start up and setting it once?

2

There are 2 answers

1
Glen Thomas On BEST ANSWER

The source code for ServicePointManager shows that the ServicePoint objects are wrapped inside WeakReference objects and stored in a Hashtable. The WeakReference type provides a reference to an object while still allowing that object to be reclaimed by garbage collection. So it might be the case that the garbage collector has disposed of the ServicePoint and the ServicePointManager has subsequently regenerated a new ServicePoint object to replace it, which would not hold the previous configuration values that the ServicePointManager does not control. There doesn't appear to be a way to configure ConnectionLeaseTimeout statically so that it will be applied to newly created ServicePoint objects.

0
Glen Thomas On

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 value. The default is 100 seconds. Each ServicePoint will use the idle time as it is set when the ServicePoint is created (a reference to the TimerThread.Queue is passed into the ServicePoint constructor), so updating the ServicePointManager.MaxServicePointIdleTime will not adjust the MaxIdleTime of any existing ServicePoint objects, so make sure to configure this before using any HTTP connections.