There was recently a good post by Abhinaba about finalizers and threads Finalizers and Thread local storage. One of the things mentioned in MSDN is this:  “Finalizers can be executed in any order”. The consequence of this is not too obvious.

Consider the case below:


class MyClass
    MyClass2 myClass2; //Member.
    /// <summary>
    /// Finalizer method
    /// </summary>
    {       myClass2.Cleanup(); //This is incorrect/

MyClass myClass = new MyClass();

Although it seems like an object of MyClass (myClass) holds a reference to myClass2, and hence it should be accessible from the finalizer, the truth is that, given the fact that the myClass object is being finalized because it has no references pointing to it (it is garbage), this could very well mean that the myClass2 object maynot have any references either (if myClass is the only one that holds a reference to it). Hence when myClass becomes garbage, GC is free to cleanup and call finalizers in any order it wants. So myClass2 might not even exist at the point of myClass’s finalizer being executed.

The golden rule here is to remember this: No managed object access should be done in Finalizers.