vendredi 27 octobre 2017

Template method pattern with IDisposable pattern in C#

I see that the common guideline to implement the disposable pattern in C# is to have an abstract base class that implements the Dispose() method from IDisposable interface and provides a protected virtual Disposable(bool) method. Then sub-classes need to override Disposable(bool) and always do something like:

if (!disposed && disposing)
{
    // dispose resources here

    disposed = true;
}

My question is: wouldn't be possible reuse this pattern? I don't like to have to manage this "disposed state" in every subclass. We could have some abstract base class like this:

public abstract class AbstractResource : IDisposable
{
    private bool myDisposed = false;

    protected abstract void ReleaseUnmanagedResources();

    protected virtual void ReleaseManagedResources()
    {
        // optionally override this to explicitly call Dispose() of other IDisposable objects
    }

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

    private void Dispose(bool disposing)
    {
        if (!myDisposed)
        {
            if (disposing)
            {
                ReleaseManagedResources();
            }

            ReleaseUnmanagedResources();

            myDisposed = true;
        }
    }

    ~AbstractResource()
    {
        Dispose(false);
    }
}

Then users of this class only need to implement ReleaseUnmanagedResources and (optionally) ReleaseManagedResources. No need to deal with booleans.

I've found that this article proposes a similar technique. But that is it! Nobody else mentions it. Are there flaws with this approach?

Aucun commentaire:

Enregistrer un commentaire