I am working on a C# application that has multiple forms.
When I open one of the forms I add an event listener like this: SomeClass.MotionCompleted += new EventHandler(HandlerMethod);
. The MotionCompleted
event is a static event.
I have noticed that after closing this form the HandlerMethod
still gets called when the event occurs which then causes an exception because it tries to update something on the form which doesn't exist anymore.
How can the event listener exist and respond to the event even though the form doesn't exist anymore? Once form.Close()
or this.Close()
is called shouldn't that automatically unhook the event listeners so that they do not get called anymore?
That's the evil of static events! :) You have a managed leak there.
Override the OnClosing of your form and deregister you handler:
protected override void OnClosing(CancelEventArgs e) {
SomeClass.MotionCompleted -= new EventHandler(HandlerMethod);
}