开发者

Implementing IDisposable on a subclass when the parent also implements IDisposable

I have a parent and child class that both need to implement IDisposable. Where should virtual (and base.Dispose()?) calls come into play? When I just override the Dispose(bool disposing) call, it feels really strange stating that I implement IDisposable without having an explicit Dispose() function (just utilizing the inherited one), but having everything else.

What I had been doing (trivialized quite a bit):

internal class FooBase : IDisposable
{
    Socket baseSocket;

    priv开发者_Python百科ate void SendNormalShutdown() { }

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

    private bool _disposed = false;
    protected virtual void Dispose(bool disposing)
    {
        if (!_disposed)
        {
            if (disposing)
            {
                SendNormalShutdown();
            }
            baseSocket.Close();
        }
    }

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

internal class Foo : FooBase, IDisposable
{
    Socket extraSocket;

    private bool _disposed = false;
    protected override void Dispose(bool disposing)
    {
        if (!_disposed)
        {
            extraSocket.Close();
        }
        base.Dispose(disposing);
    }

    ~Foo()
    {
        Dispose(false);
    }

}


When I just override the Dispose(bool disposing) call, it feels really strange stating that I implement IDisposable without having an explicit Dispose() function (just utilizing the inherited one), but having everything else.

This is something you shouldn't be concerned with.

When you subclass an IDisposable class, all of the "Dispose pattern" plumbing is already being handled for you by the base class. You really should do nothing but override the protected Dispose(bool) method, and track whether you've been disposed already (to properly raise ObjectDisposedException.)

For details, see my blog post on Subclassing from an IDisposable class.


Also, often, it's a good idea to consider encapsulating the IDisposable class instead of subclassing it. There are times when subclassing an IDisposable class is appropriate, but they are somewhat rare. Encapsulation is often a better alternative.


Why complicate things when you don't need to?

Since you don't encapsulate any unmanaged resources, you don't need all that mucking about with finalization. And, your classes are internal, which suggests that you control the inheritance hierarchy within your own assembly.

So, the straighforward approach would be:

internal class FooBase : IDisposable 
{ 
  Socket baseSocket; 

  private void SendNormalShutdown() 
  { 
    // ...
  } 

  private bool _disposed = false; 

  public virtual void Dispose() 
  { 
    if (!_disposed)
    { 
      SendNormalShutdown(); 
      baseSocket.Close(); 
      _disposed = true;
    } 
  } 
} 

internal class Foo : FooBase
{ 
  Socket extraSocket; 

  private bool _disposed = false; 

  public override void Dispose()
  { 
    if (!_disposed)
    { 
      extraSocket.Close(); 
      _disposed = true;
    } 

    base.Dispose(); 
  } 
} 

Even when you do have unmanaged resources, I'd say you're much better off encapsulating them in their own disposable class and using them like you'd use any other disposable; as straighforward as the code above.


The idea of this pattern is that you override the virtual Dispose method, calling base.Dispose if necessary. The base class takes care of the rest, calling the virtual Dispose method (and hence the correct implementation). The subclass should not need to also implement IDisposable (it is IDisposable via inheritance)


I always turn to Joe Duffy's very in-depth study on this pattern. For me, his version is Gospel.

http://joeduffyblog.com/2005/04/08/dg-update-dispose-finalization-and-resource-management/

The first thing to remember is that a finalizer is not needed most of the time. It's for clearing up unmanaged resources where you are directly holding native resources, i.e. only resources that do not have their own finalizer.

Here's an example for a base-class subclass pair.

// Base class

    #region IDisposable Members

    private bool _isDisposed;

    public void Dispose()
    {
        this.Dispose(true);
        // GC.SuppressFinalize(this); // Call after Dispose; only use if there is a finalizer.
    }

    protected virtual void Dispose(bool isDisposing)
    {
        if (!_isDisposed)
        {
            if (isDisposing)
            {
                // Clear down managed resources.

                if (this.Database != null)
                    this.Database.Dispose();
            }

            _isDisposed = true;
        }
    }

    #endregion


// Subclass

    #region IDisposable Members

    private bool _isDisposed;

    protected override void Dispose(bool isDisposing)
    {
        if (!_isDisposed)
        {
            if (isDisposing)
            {
                // Clear down managed resources.

                if (this.Resource != null)
                    this.Resource.Dispose();
            }

            _isDisposed = true;
        }

        base.Dispose(isDisposing);
    }

    #endregion

Note that the subclass has its own _isDisposed member. Also note null-checking on resources since you don't want any exceptions in these blocks.

Luke


The child class should override the virtual Dispose, do any disposing specific to the subclass, and call the superclass' Dispose, which in turn will do its own work.

EDIT: http://davybrion.com/blog/2008/06/disposing-of-the-idisposable-implementation/ is the pattern I follow in such cases. Not the 'Disposable' class specifically, but the inheritance and overrides.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜