Disposing of Objects with long living dependencies

Posted by Ray Booysen on Stack Overflow See other posts from Stack Overflow or by Ray Booysen
Published on 2010-03-24T09:36:35Z Indexed on 2010/03/25 14:33 UTC
Read the original article Hit count: 357

Filed under:
|
|
public class ABC
{
    public ABC(IEventableInstance dependency)
    {
        dependency.ANewEvent += MyEventHandler;
    }

    private void MyEventHandler(object sender, EventArgs e)
    {
        //Do Stuff
    }
}

Let us say that an instance of ABC is a long living object and that my dependency is an even longer running object. When an instance of ABC needs to be cleaned up, I have two options.

One I could have a Cleanup() method to unsubscribe from the ANewEvent event or I could implement IDisposable and in the Dispose unwire the event. Now I have no control over whether the consumer will call the dispose method or even the Cleanup method should I go that route.

Should I implement a Finaliser and unsubscribe then? It feels dirty but I do not want hanging instances of ABC around.

Thoughts?

© Stack Overflow or respective owner

Related posts about dispose

Related posts about long-living