开发者

If Form1 opens Form2 and registers for Form2.TextChanged, do I need to unregister Form2.TextChanged from within Form1 if Form2 is closing?

This is another question about well disposing objects from .NET. After having read a lot of different arcticles about dispose best practices (and people opinions), I was not able to get an answer for that one. I have 2 forms, Form1 and Form2.

Form1

void ShowFormButton_Click(object sender, eventargs e)
{
    Form2 form = new Form2();
    form.TextChanged += n开发者_如何学Cew eventhandler(form_TextChanged);
    form.Show(this);
}

Form2

void CloseFormButton_Click(object sender, eventargs e)
{
    Close();
}

When calling Close() in Form2, the Form2 should have is dispose() method call because it was opened by calling is Show() method but because Form1 has registered for the TextChanged event or Form2, will this keep Form2 from being disposed or make the process of disposing by the GC less efficient?

Thanks in advance


Form2 form = new Form2(); 
form.TextChanged += new eventhandler(form_TextChanged);

This means, that Form2 instance has reference to Form1 form_TextChanged method. When Form2 is closed, this doesn't prevent it to be collected, so in this case unsubscribing is not obligatory.

Let's say that Form2 subscribes to Form1 event. In this case, when Form2 is closed, Form1 still has active reference to Form2, and Form2 cannot be collected, creating memory leak.

So, the answer depends on subscription direction and event source/subscriber life time. In any case, if something is not clear, it is better to unregister events.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜