Cook Computing

Object Disconnection

June 5, 2003 Written by Charles Cook

Andy McMullan pointed out a obscure feature of .NET Remoting yesterday. If a client acquires an object in another AppDomain (remoted or in-process) and then sets the reference to null you might think that the garbage collector would clean up the dangling proxy object and so release the connection to the object, which would then be eligible for collection itself. In fact the connection is only broken when its lease times out, which might be a long time after a number of garbage collections.

Of course, if the object acquires expensive resources then it would make sense to provide a Dispose method which the client can call to explicitly free up the resources. However the delayed disconnection could cause a problem where a large number of inter-AppDomain objects are acquired within the lease timeout timespan, purely because of the memory allocated for the objects themselves. The default timespan is 5 minutes if no calls are made on the object and 2 minutes from the last call, which means a hgh frequency of object creation could cause the GC heap to expand unacceptably.

So, if this is a problem in a particular scenario, is there a way in which the client can forcibly disconnect the object and implicitly make the object available for GC? Andy mentioned the RemotingServices.Disconnect method and I modified my client test code to call this in a Dispose method implemented on the target object. The ITrackingHandler implementation does log a disconnection (and the client cannot make any further calls on the object) but the object is not GC'ed until the lease times out, after another disconnection event is logged for the same object. In case there was a problem with calling Disconnect from within a call to the object being disconnected, I arranged for another object within the same AppDomain to call Disconnect but the results were the same.