StackOverflow when closing my form
I am trying to close my main(the parent) form when a child form is being closed. However this gives me a StackOverflow exception.
However if I call _child.Dispose on the FormClosed event it works as intended. Should I do this? Why should I call Dispose? (because of the .Show() it shouldn't be neceserry right?
A small demo:
public partial class frmChild : Form
{
public frmChild()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
this.Close();
}
}
public partial class frmParent : Form
{
private frmChild _child;
public frmParent()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
_child = new frmChild();
_child.FormClosed += child_FormClosed;
_child.Show(this);
}
void child_FormClosed(object sender, FormClosedEventArgs e)
{
//_child.Dispose(); <-- uncomment and it works
this.Close(); // <-- StackOverflow exception
}
}
The solution, commented by Teoman Soygul (for future reference):
Closing the main form with this.Close(); signals all ch开发者_开发技巧ild windows to close in order so that creates the infinite loop
After calling this.Close() in the parent it will signal all children to Close aswel, which will send another FormClosed event...
I solved it by not specifieing the owner in _child.Show();
I didn't use the owner anyway.
Since every time you call this.Close();
the FormClosed
event gets fired which then calls this.Close();
again, you create an infinite loop. On the other hand, if the form is already disposed (as in you uncomment the dispose line), the FormClosed
event does not get fired again as the object is already disposed. So disposing of the form on the event is right, or if you don't want to do that, you can add an additional check with a private bool field like:
if (!formClosed)
{
this.formClosed = true;
this.Close();
}
精彩评论