Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
422 views
in Technique[技术] by (71.8m points)

c# - Do I need to unsubscribe events in my Form?

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.

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 );
}
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

In this situation I beleive it is OK not to unsubscribe because the TextBox to which you're subscribing is wholly contained within the parent control (or that's what I'm assuming.)

Therefore when no further references to the parent control exist, there won't be any external references to the TextBox and so both objects will become eligible for GC.

There are situations when you should unsubscribe from events to prevent memory leaks because the reference held by the event (in it's list of subscribers) is just the same as any other reference and would prevent the subscriber from being GC'd.

Such situations can occur when an object subscribes to an event on an external object (i.e. not owned by this object.) In this situation the subscriber would only become eligible for GC after the subscribed-to object was eligible for GC.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...