1

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 += new 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

Benoit Drapeau
  • 614
  • 1
  • 6
  • 13

1 Answers1

1
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.

Alex F
  • 39,172
  • 34
  • 138
  • 200