我试图在关闭子窗体时关闭我的主(父)窗体。然而,这给了我一个 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 评论(供以后引用):
Closing the main form with this.Close(); signals all child windows to close in order so that creates the infinite loop
在父级中调用 this.Close() 后,它将向所有子级发出 Close aswel 信号,这将发送另一个 FormClosed 事件...
我通过不在 _child.Show();
中指定所有者来解决它,反正我没有使用所有者。
最佳答案
因为每次调用 this.Close();
时,FormClosed
事件都会被触发,然后再次调用 this.Close();
,你创建了一个无限循环。另一方面,如果表单已被处理(如取消注释处理行),则不会再次触发 FormClosed
事件,因为对象已被处理。因此,在事件中处理表单是正确的,或者如果您不想这样做,您可以添加一个带有私有(private) bool 字段的额外检查,例如:
if (!formClosed)
{
this.formClosed = true;
this.Close();
}
关于c# - 关闭表单时的 StackOverflow,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6124863/