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

cevent handlingevents

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

Best Answer

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.