views:

38

answers:

1
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?

+1  A: 

I read this on MSDN:

Because the Dispose method must be called explicitly, objects that implement IDisposable must also implement a finalizer to handle freeing resources when Dispose is not called. By default, the garbage collector automatically calls an object's finalizer prior to reclaiming its memory. However, once the Dispose method has been called, it is typically unnecessary for the garbage collector to call the disposed object's finalizer. To prevent automatic finalization, Dispose implementations can call the GC.SuppressFinalize method.

So to be on the safe side in this case, I'd implement both IDisposable and a finalizer. And I agree, it's a bit dirty, but then again, that's the price you pay when dealing with long-lifespan objects.

Prutswonder