C# .NET proper event subscribing and un-subscribing

旧城冷巷雨未停 提交于 2021-02-08 05:01:06

问题


I have an application that runs continuously, it creates and destroys classes some of which have events like mouse click events and the like... First question is what is the proper way to unsubscribe? If the subscribe looks like this:

Panel1.MouseClick += new MouseEventHandler(Action_MouseClick);

is it proper to unsubscribe like this:

Panel1.MouseClick -= new MouseEventHandler(Action_MouseClick);

OR is it ok to do this:

Panel1.MouseClick -= Action_MouseClick;

or is either way ok?

My other question is is If I use the Microsoft Visual C# studio to create the events through the designer, does it automatically unsubscribe as part of the 'Dispose' method? Or do I still need to put the unsubscribe method in the code?


回答1:


Either way of unsubscribing will have the same effect, and both are correct.

As for your other question .. if you use the designer to create events for controls on a form, when the form is disposed the source of the events no longer exists, so they won't be called. I guess I'm saying it isn't necessary to detach those events.




回答2:


My other question is is If I use the Microsoft Visual C# studio to create the events through the designer, does it automatically unsubscribe as part of the 'Dispose' method? Or do I still need to put the unsubscribe method in the code?

From memory: no, it won't generate the un-subscribe code.

You can double check this yourself by opening the classname.designer.cs file and examining the generated Dispose method.




回答3:


The designer code won't automatically unsubscribe, but the subscriptions should not keep the controls alive as long as the form and all of its controls are no longer accessible from the application code. Lingering event handlers are mainly a problem when the subscriber and event producer have different lifetimes, which generally shouldn't be the case for a Form and its controls.

If you create/remove controls dynamically, you will probably want to manage the events, though it's not strictly necessary if the removed controls are no longer referenced and the removed controls stop firing events.



来源:https://stackoverflow.com/questions/3241074/c-sharp-net-proper-event-subscribing-and-un-subscribing

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!