What are finalisers for?

烂漫一生 提交于 2019-12-01 16:14:20

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).

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

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.

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.

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.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!