Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

EventHandlers and C# Classes destructor/Dispose

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 constructor:

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

I need to 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, and then the class instance goes out of scope. For another it stays in the 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 don't want to leak memory. When and how should I unsubscribe?

like image 797
Sarah Fordington Avatar asked Aug 17 '09 12:08

Sarah Fordington


People also ask

What is the role of event handlers?

In programming, an event handler is a callback routine that operates asynchronously once an event takes place. It dictates the action that follows the event. The programmer writes a code for this action to take place. An event is an action that takes place when a user interacts with a program.

What are event handlers example?

In general, an event handler has the name of the event, preceded by "on." For example, the event handler for the Focus event is onFocus. Many objects also have methods that emulate events. For example, button has a click method that emulates the button being clicked.

How do you call an event handler in C#?

In C# 6.0 and above you can use Null Propagation: handler?. Invoke(this, e); handler(this, e) will call every registered event listener.


2 Answers

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;
    }
}
like image 120
Thomas Levesque Avatar answered Oct 18 '22 04:10

Thomas Levesque


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.

like image 6
Rich Schuler Avatar answered Oct 18 '22 05:10

Rich Schuler