Reputation: 10294
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?
Upvotes: 2
Views: 1958
Reputation: 21909
Someclass.MotionCompleted -= new EventHandler(HandlerMethod);
This article shows a lot of tips regarding events in C#:
https://csharpindepth.com/articles/Events
Upvotes: 2
Reputation: 662
You have to unhook in manually:
SomeClass.MotionCompleted -= HandlerMethod;
Upvotes: 0
Reputation: 11384
To add to all the duplicate answers you can also unhook this way:
SomeClass.MotionCompleted -= HandlerMethod;
The output assembly code will be the same whether you use -= HandlerMethod
or -= new EventHandler(HandlerMethod)
.
Upvotes: 1
Reputation: 26468
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);
}
Upvotes: 7
Reputation: 4065
Events are strong reference : they cannot be garbage collected unless you explicitely dereferece them.
That's why I suggest youw rite a subscribe and an unsubscibe methods that will do their jobs and centralize this hooks (which will results in memory leaks if you don't free them)
private void subscribeAll()
{
SomeClass.MotionCompleted += new EventHandler(HandlerMethod);
// other subscription
}
private void unSubscribeAll()
{
SomeClass.MotionCompleted -= new EventHandler(HandlerMethod);
// other subscription
}
Upvotes: 0
Reputation: 12562
Not exactly. The form is not collected by the garbage collector because the event handler is still there. The static event handlers don't get unhooked by themselves. You can unhook any assigned event in the form onClosing method like:
SomeClass.MotionCompleted -= new EventHandler(HandlerMethod);
After that everything should work.
Upvotes: 0
Reputation: 3766
You need to manually unhook the event like this:
SomeClass.MotionCompleted -= new EventHandler(HandlerMethod);
Upvotes: 0
Reputation: 5885
You can use this sample of code :
SomeClass.MotionCompleted -= new EventHandler(HandlerMethod);
However, you must be careful to unhook your event from the same instance of the object containing HandlerMethod
that the one which registered it.
Upvotes: 0
Reputation: 6085
SomeClass.MotionCompleted -= new EventHandler(HandlerMethod);
just change the "+" to "-"
Upvotes: 0