Alex Rivera | Logout

When should I implement IDisposable?

Asked 2010-03-12T09:04:46.207
46

What is the best practice for when to implement IDisposable?

Is the best rule of thumb to implement it if you have one managed object in the class, or does it depend if the object was created in the class or just passed in? Should I also do it for classes with no managed objects at all?

Edit
Report

1 Answer

14

While everyone has mentioned (unmanaged) resources, I have another thing to add: I use it when I need to eliminate event handler hookups that would otherwise prevent a class from going out of scope and being garbage collected.

As an example, I have a service which gets injected in to a child view, that child view will subscribe to various async finished type events on the service. The owner of that child view has no idea what the concrete type is, it simply has it as an interface. The service may go out of scope at some arbitrary point in the future, and I don't want it hanging around not being GC'ed. Upon getting rid of that child view, the owner will call Dispose on it to give it the chance to unhook any event handlers. Here is a slightly contrived (and very pseudo code) example, note how the interface for the child view also implements IDisposable.

public class OwnerView {

    public OwnerView() {
        _childView = new ChildView(myServiceReference);
    }

    public void CloseChildView() {
        if (childView != null) {
            _childView.Close();
            _childView.Dispose();
        }

        _childView = null;
    }

    private IChildView _childView;
}

public class ChildView : IChildView {

    public ChildView(MyService serviceRef) {
        _serviceRef = serviceRef;
        _serviceRef.GetSettingsAsyncFinished += new EventHandler(someEventHandler);
    }

    public void IDisposable.Dispose() {
        _serviceRef -= someEventHandler;
    }

    private MyService _serviceRef;
}

public interface IChildView : IDisposable {
    void DoSomething();
    ... etc ...
}

There are far more authoritative comments about this from others on SO, like Do event handlers stop garbage collection from occuring? and answered 2010-03-12T11:00:00.527

Your Answer