What are finalisers for?

2020-04-02 09:48发布

问题:

I have been programming in .NET for four years (mostly C#) and I use IDiposable extensively, but I am yet to find a need for a finaliser. What are finalisers for?

回答1:

A finalizer is a last ditch attempt to ensure that something is cleaned up correctly, and is usually reserved for objects that wrap unmanaged resources, such as unmanaged handles etc that won't get garbage collected.

It is rare indeed to write a finalizer. Fortunately (and unlike IDisposable), finalizers don't need to be propagated; so if you have a ClassA with a finalizer, and a ClassB which wraps ClassA, then ClassB does not need a finalizer - but quite likely both ClassA and ClassB would implement IDisposable.

For managed code, IDisposable is usually sufficient. Even if you don't clean up correctly, eventually the managed objects will get collected (assuming they are released).



回答2:

Finalizers are only for freeing unmanaged resources like GDI bitmap handles for example. If you don't allocate any unmanaged resources then you don't need finalizers. In general it's a bad idea to touch any managed object in a finalizer because the order of finalization is not guaranteed.

One other useful technique using a finalizer is to assert that Dispose has been called when the application is required to do so. This can help catch coding errors in a DEBUG build:

void Dispose()
{
  GC.SuppressFinalize(this);
}
#if DEBUG
~MyClass()
{
  Debug.Fail("Dispose was not called.");
}
#endif


回答3:

Finalizers are meant as a mechanism to release resources not controlled by garbage collector, like an unmanaged handle. While Dispose might do it, it isn't guaranteed that the consumer will call it.



回答4:

Finalizers are for cleaning up resources if they were not disposed.

IE, nothing enforces that you ever call Dispose(), but Finalizers are called automatically by the garbage collector.

This functionality should not be relied upon, as there is no guarantee when (or if) garbage collection will get to your object.



回答5:

Wikipedia says:

...a finalizer is a piece of code that ensures that certain necessary actions are taken when an acquired resource... is no longer being used [because the owning object has been garbage collected]

And if you're not using a finaliser when you're writing IDisposables you've quite possibly got memory leaks, because there's no guarantee an owner is actually going to call Dispose().

MS themselves recommend you write something similar to this into your implementers:

    public void Dispose()
    {
        this.Dispose(true);
    }

    protected virtual void Dispose(bool disposing)
    {
        if (!this.isDisposed)
        {
            if (disposing)
            {
                GC.SuppressFinalize(this);
            }
        }
        //Dispose of resources here
        this.isDisposed = true;
    }

    ~DisposableSafe()
    {
        this.Dispose(false);
    }

    private bool isDisposed = false;

Personally, I can't stand the copy-paste so I tend to wrap that in an abstract class for reuse.