Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Event Driven Programming

Tags:

c#

I've been reading this MSDN article and this question to try to understand events in .NET. Unfortunately, its not clicking for me and I'm having a lot of trouble. I'm trying to integrate this technique into my project, with little success.

Basically, I've got this class that will read numbers. Whenever it encounters a new number, I want it to fire an event called numberChanged.

So, I set up my event public event EventHandler numberChanged;. Later on, I fire my event when it encounters a number than isn't the same as the previous one.

if(currentNumber != previousNumber){
     if(numberChanged != null){
          numberChanged(this, new EventArgs());
     }
}

But then I'm having trouble 'subscibing' to this event. If I do numberChanged += [something to do here] it errors saying that numberChanged is an event and not a type.

Is my explanation clear enough for some advice to be offered? Many thanks.

like image 563
JShell Avatar asked Dec 19 '22 02:12

JShell


1 Answers

There are a number of ways to handle it, the most basic is to create a function:

public void MyNumberChangedHandler(object sender, EventArgs e)
{
    //Your code goes here that gets called when the number changes
}

You then subscribe (one time only, usually in the constructor) by going:

numberChanged += MyNumberChangedHandler;

Or, you can use something called an anonymous (lambda) method, which is also assigned in your constructor (typically):

numberChanged += (sender, e) => {
    //Your code here to handle the number changed event
};

To expand a little bit, care must be taken when using the lambda approach since you can create memory leaks and zombie objects. The .NET memory garbage collector is a mark-and-sweep system that removes objects when they are no longer in use. This post shows how hard it is to remove lambda event handlers: How to remove a lambda event handler .

Having an active event handler can keep your object alive even if it has been disposed! Here is an example of creating a zombie object (doesn't run in Fiddle but you can copy to your own console app) https://dotnetfiddle.net/EfNpZ5

Prints out:

I'm still alive
I'm still alive
I was disposed!
Press any key to quit
I'm still alive
I'm still alive
I'm still alive.
like image 86
Ron Beyer Avatar answered Feb 16 '23 00:02

Ron Beyer