views:

975

answers:

2

Hi,

I'm a bit confused about C# Classes and their deconstructor.

I have to consume a few event handlers in a class instance I'm getting in the contructor:

 public Foo(IFooHandler handler)
 {
     handler.Load += Load;
     handler.Close += Close;
 }

Now my question is that I need unsubscribe to that event when the Foo class is destroyed, do I implement IDisposable and unsubscribe in there or in a deconstructor? I need to consume those events, I can't do it another way.

For one of the classes, I create an instance, check progress then the class instance goes out of scope. For another it stays in teh MainForm until the form is closed. The first is what I'm worried about because it may still have a reference to that event handler and not properly go.

I dont want to leak memory. When and how should I unsubscribe?

+8  A: 

Don't do it in the destructor, because it won't be called while the event handlers are attached : when you attach an instance method of Foo as a handler for an event of Bar, Bar will hold a reference to Foo, so Foo won't be garbage collected, and its destructor won't be called.

You should implement IDisposable, and dispose your object explicitly

public void Dispose()
{
    if (handler != null)
    {
        handler.Load -= Load;
        handler.Close -= Close;
    }
}
Thomas Levesque
Ah! I thought we shouldnt implement IDisposable unless we're cleaning up unmanaged code?
Sarah Fordington
IDisposable can be implemented for other reasons, it's not limited to cleaning unmanaged resources...
Thomas Levesque
If you take a look at the common Disposable Pattern, there is a path for handling managed and unmanaged resources. Mostly you have only unmanaged resources and / or managed ones. But for your case it is also okay just to have managed resources which should be cleaned.
Oliver
To complete Oliver's comment, here's a useful link : http://msdn.microsoft.com/en-us/library/b1yfkh5e.aspx
Thomas Levesque
+1  A: 

If you ever face the problem of having class A be a long lived class and class(es) B be short lived ones that subscribe to events of class A then you probably would be interested in the Weak Event Pattern. It can be a problem that you do not discover is one until it is to late i.e. Princeton self driving car.

Qberticus