Are finalizers allowed to use the methods of other managed classes?

I was sure that the answer was no, as explained in Overriding the Finalize Method and Object.Finalize documentation .

However, when I accidentally looked FileStreamin Reflector, I found that it can actually call just such a method from the 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 began to wonder if this will always work because of how it is written, and therefore whether “not touching managed classes from finalizers” is just a guide that could be broken for a good reason and the necessary knowledge to make it is right.

, , , "" , , . , SafeFileHandle , Dispose fail, ... ?

: , ? , , , .

. , SafeFileHandle , , Dispose(). SafeHandle : InternalDispose InternalFinalize, InternalDispose. ? ?...

+3
1

, . , , . null finalizable , .

. , , , , .

+2

Source: https://habr.com/ru/post/1744574/


All Articles