Proper disposal and finalization of objects

suggest change

Dispose and a finalizer serve different purposes. A class that owns unmanaged resources often implements both. It then has to handle two cases:

One solution is writing the cleanup code in such a way that running it once or twice would produce the same result as running it only once. Feasibility depends on the nature of the cleanup, for instance:

A safer solution is ensuring by design that the cleanup code is called once and only once whatever the external context. This can be achieved the “classic way” using a dedicated flag:

public class DisposableFinalizable1: IDisposable
{
    private bool disposed = false;

    ~DisposableFinalizable1() { Cleanup(); }

    public void Dispose() { Cleanup(); }

    private void Cleanup()
    {
        if(!disposed)
        {
            // Actual code to release resources gets here, then
            disposed = true;
        }
    }
}

Alternatively, GC.SuppressFinalize skips the finalizer after Dispose. The standard pattern is a protected Dispose(bool disposing) plus SuppressFinalize. The sample below can still run Cleanup twice if the finalizer races with Dispose, because nothing makes Cleanup single-threaded or idempotent:

public class DisposableFinalizable2 : IDisposable
{
    ~DisposableFinalizable2() { Cleanup(); }

    public void Dispose()
    {
        Cleanup();
        GC.SuppressFinalize(this);
    }

    private void Cleanup()
    {
        // Actual code to release resources gets here
    }
}

Feedback about page:

Feedback:
Optional: your email if you want me to get back to you:



Table Of Contents