关闭表单时的 StackOverflow
当关闭子表单时,我试图关闭我的主(父)表单。然而,这给了我一个 StackOverflow 异常。
但是,如果我在 FormClosed 事件上调用 _child.Dispose ,它就会按预期工作。我应该这样做吗?我为什么要调用 Dispose? (因为 .Show() 它不应该是必需的,对吧?
一个小演示:
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
}
}
Teoman Soygul 评论的解决方案(供将来参考):
关闭主窗体 this.Close();向所有孩子发出信号 窗户按顺序关闭,以便 创建无限循环
在父级中调用 this.Close() 后,它将向所有子级发出关闭信号,这将发送另一个 FormClosed 事件... 我通过不在 _child.Show();
中指定所有者解决了这个问题,无论如何我都没有使用所有者。
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 child
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.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
由于每次调用
this.Close();
时,FormClosed
事件都会被触发,然后再次调用this.Close();
,您创建无限循环。另一方面,如果表单已被释放(如取消注释 dispose 行),则FormClosed
事件不会再次触发,因为对象已被释放。因此,在事件上处理表单是正确的,或者如果您不想这样做,您可以使用私有布尔字段添加额外的检查,例如:Since every time you call
this.Close();
theFormClosed
event gets fired which then callsthis.Close();
again, you create an infinite loop. On the other hand, if the form is already disposed (as in you uncomment the dispose line), theFormClosed
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: