EventHandlers and C # destructor / Dispose class

I got a little confused in C # classes and their deconstructor.

I need to use several event handlers in an instance of the class that I get in the constructor:

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

I need to unsubscribe from this event when the Foo class is destroyed. Do I perform IDisposable and unsubscribe there or in the deconstructor? I need to destroy these events, I can not do it differently.

For one of the classes, I create an instance, check the progress, and then the class instance goes out of scope. For another, it remains in MainForm until the form is closed. Firstly, this is what I'm worried about, because it still has a link to this event handler, and not to the correct operation.

I do not want a memory leak. When and how should I unsubscribe?

+22
c # events winforms delegates
Aug 17 '09 at 12:51
source share
2 answers

Do not do this in the destructor because it will not be called during the event handler attachment: when you attach the Foo instance method as a Bar event handler, the Bar will contain a reference to Foo, so Foo will not collect garbage and its destructor will not be called .

You must implement IDisposable and explicitly deny your object

 public void Dispose() { if (handler != null) { handler.Load -= Load; handler.Close -= Close; } } 
+24
Aug 17 '09 at 13:05
source share
β€” -

If you ever have to face the problem that class A is a long-lived class and classes B, then these are short-lived ones that subscribe to events of class A, then you will probably be interested in a Weak event pattern . This may be a problem that you do not discover until it is too late, that is, Princeton automaker.

+3
Aug 22 '09 at 6:26
source share



All Articles