Tuesday, September 25, 2007

A "weak" reason to invoke garbage collection

Call GC.Collect() is generally considered unnecessary and can actually disrupt the smooth functioning of the .NET garbage collector.  Dennis Dietrich gives a scenario where it is reasonable to call the garbage collector in your code.  His example outlines a situation where you want to test that all references to an object have been deleted at some point in the program so that the object can be garbage collected.  The catch-22 is if you maintain a reference to the object to see if it still exists, it cannot be collected.

Enter WeakReference.  This class allows you to maintain a reference to an object while letting it be collected if need be.  In the time between the object's destruction and its pickup by GC, a WeakReference allows you to continue to use the object.  Now continuing to use an object that's in limbo may seem like a bad idea, as the garbage man could drive by anytime.  But here's an interesting scenario where you may wish to keep a WeakReference so that you could have the possibility of turning it back into a strong reference (and thus keep the object from being collected).

In our testing case, we wish to do the opposite, make sure we cannot continue to reference the object.  After GC.Collect() is called, we check the IsAlive property of our WeakReference. 

On a side note, it's interesting that something so fragile implements ISerializable.

No comments: