简体   繁体   中英

C# .NET proper event subscribing and un-subscribing

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?

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.

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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM