开发者

How to unhook event handlers in C#

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 ca开发者_开发知识库n 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);
}


Someclass.MotionCompleted -= new EventHandler(HandlerMethod);

This article shows a lot of tips regarding events in C#:
https://csharpindepth.com/articles/Events


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).


SomeClass.MotionCompleted -= new EventHandler(HandlerMethod);

just change the "+" to "-"


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.


You need to manually unhook the event like this: SomeClass.MotionCompleted -= new EventHandler(HandlerMethod);


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.


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
}


You have to unhook in manually:

SomeClass.MotionCompleted -= HandlerMethod;
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜