Are finalizers ever allowed to call other managed classes' methods?

Posted by romkyns on Stack Overflow See other posts from Stack Overflow or by romkyns
Published on 2010-05-07T23:44:12Z Indexed on 2010/05/07 23:48 UTC
Read the original article Hit count: 297

Filed under:
|
|

I used to be pretty sure the answer is "no", as explained in Overriding the Finalize method and Object.Finalize documentation.

However, while randomly browsing through FileStream in Reflector, I found that it can actually call just such a method from a finalizer:

private SafeFileHandle _handle;

~FileStream()
{
    if (this._handle != null)
    {
        this.Dispose(false);
    }
}

protected override void Dispose(bool disposing)
{
    try
    {
        ...
    }
    finally
    {
        if ((this._handle != null) && !this._handle.IsClosed)  // <=== HERE
        {
            this._handle.Dispose();   // <=== AND HERE
        }
        [...]
    }
}

I started wondering whether this will always work due to the exact way in which it's written, and hence whether the "do not touch managed classes from finalizers" is just a guideline that can be broken given a good reason and the necessary knowledge to do it right.

I dug a bit deeper and found out that the worst that can happen when the "rule" is broken is that the managed object being accessed had already been finalized, or may be getting finalized in parallel on a separate thread. So if the SafeFileHandle's finalizer didn't do anything that would cause a subsequent call to Dispose fail then the above should be fine... right?

Question: so there might after all be situations in which a method on another managed class may be called reliably from a finalizer? I've always believed this to be false, but this code suggests that it's possible and that there can be good enough reasons to do it.

Bonus: Observe that the SafeFileHandle will not even know it's being called from a finalizer, since this is just a normal call to Dispose(). The base class, SafeHandle, actually has two private methods, InternalDispose and InternalFinalize, and in this case InternalDispose will be called. Isn't this a problem? Why not?...

© Stack Overflow or respective owner

Related posts about finalizer

Related posts about dispose