我需要取消订阅表单中的事件吗? [英] Do I need to unsubscribe events in my Form?

查看:73
本文介绍了我需要取消订阅表单中的事件吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图了解如何取消预订 Control 事件。假设我有一个文本框,并且已经使用WinForms设计器订阅了 TextChanged 事件。

I'm trying to understand how a Control events are unsubscribed. Suppose I have a textbox and I have subscribed the TextChanged event using the WinForms designer.

<$ c是文本框析构函数中的$ c> TextChanged 事件自动取消订阅,或者我必须明确取消订阅 >避免内存泄漏?

Is the TextChanged event automatically unsubscribed in the Textbox destructor, or must I explicitly unsunscribe to avoid memory leaks?

public void InitializeComponents()
{
    ...
    this.emailTextBox.TextChanged += emailTextBox_TextChanged;
    ...
}

public override void Dispose()
{
    if( disposing )
    {
        // DO I REALLY NEED THIS LINE?
        this.emailTextBox.TextChanged -= emailTextBox_TextChanged;
        if(components != null)
        {
            components.Dispose();
        }
    }
    base.Dispose( disposing );
}


推荐答案

订阅事件的任何对象寿命较长的对象中的数据应实现 IDisposable ,并且应在 Dispose d时取消订阅这些事件。从概念上讲,没有理由在处理对象时不让其取消所有事件的订阅,因为这样做可以避免出现事件的对象寿命超出预期的问题。不幸的是,.NET中的事件体系结构没有提供机制来方便地确保在处理对象时清除事件,而在处理对象时使代码取消订阅一堆事件可能会使得很难确保确实存在的少数事件需要清理的就是其中的一个。

Any object which subscribes to events from a longer-lived object should implement IDisposable and should unsubscribe those events when it is Disposed. Conceptually, there's no reason why objects shouldn't unsubscribe from all events when they are disposed, since doing so would avoid problems if an object whose events one subscribed turned out to live longer than expected. Unfortunately, the event architecture in .NET provides no mechanism for conveniently ensuring that events get cleaned up when objects are disposed, and having code unsubscribe a bunch of events when an object is disposed may make it harder to make sure that the few events which really need to be cleaned up are among the ones that are.

这篇关于我需要取消订阅表单中的事件吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆