简体   繁体   English

C#.NET适当的事件订阅和取消订阅

[英]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? 我的另一个问题是,如果我使用Microsoft Visual C#Studio通过设计器创建事件,它是否会作为“处置”方法的一部分自动退订? Or do I still need to put the unsubscribe method in the code? 还是我仍然需要在代码中放入unsubscribe方法?

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? 我的另一个问题是,如果我使用Microsoft Visual C#Studio通过设计器创建事件,它是否会作为“处置”方法的一部分自动退订? Or do I still need to put the unsubscribe method in the code? 还是我仍然需要在代码中放入unsubscribe方法?

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. 您可以通过打开classname.designer.cs文件并检查生成的Dispose方法来自己仔细检查。

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. 当订户和事件生产者的生存期不同时,缠留事件处理程序主要是一个问题,而对于Form及其控件,通常不应该这样。

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. 如果动态创建/删除控件,则可能会想要管理事件,但是如果不再引用删除的控件并且删除的控件停止触发事件,则并不是严格必须的。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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