Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What happens when an event fires and tries to execute an event-handler in an object that no longer exists?

In one class, ClassA, I have a timer object. In this class I register the event handlers for the timer elapsed event. In another class, ClassB, I have a public event-handler for the timer elapsed event. So I register the event-handler from ClassB in ClassA as follows:

myTimer.Elapsed += ClassBInstance.TimerElapsed

What happens if I were to create a new instance of ClassBInstance and the timer elapsed event fires when the previous instance of ClassB's event-handler is still tied to the Elapsed event of the timer?

For example:

ClassB classBInstance = new ClassB();
myTimer.Elapsed += classBInstance.TimerElapsed

classBInstance = new ClassB();
myTimer.Elapsed += classBInstance.TimerElapsed
like image 901
Draco Avatar asked May 29 '09 06:05

Draco


People also ask

What happens if an event occurs and there is no event handler to respond to the event?

TF: if an event occurs and there is not event handler to respond to that event, the event ins ignored.

What happens when an object falls out of scope and fails to unsubscribe to an event to which it had previously subscribed?

It will call method of disposed object.

What is the purpose of the event handlers in the JavaScript?

JavaScript Event Handlers Event handlers can be used to handle and verify user input, user actions, and browser actions: Things that should be done every time a page loads. Things that should be done when the page is closed. Action that should be performed when a user clicks a button.

What does an event handler do?

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.


2 Answers

AFAIK, ClassBInstance is not garbage collected as long as there are events registered, because the event holds a reference to it.

You have to make sure that you unregister all events of instances that are no longer in use.

Important are cases where the registered instance is IDisposable, because the event could be fired when the instance is disposed. In this cases I found it easiest to let the instance register itself, and unregister in Dispose.

like image 143
Stefan Steinegger Avatar answered Sep 28 '22 12:09

Stefan Steinegger


Events are implemented such that as long as your publisher is alive all subscribers will be kept alive by the publisher even if you don't hold any other references to these.

Of course this also implies, that you must detach subscribers, if you want them to be cleaned-up independently of the publisher.

like image 37
Brian Rasmussen Avatar answered Sep 28 '22 12:09

Brian Rasmussen