像这样从 Invoke
中关闭表单:
Invoke(new Action(() => {
Close();
MessageBox.Show("closed in invoke from another thread");
new Form1();
}));
表单一关闭就抛出异常:
Invoke or BeginInvoke cannot be called on a control until the window handle has been created.
但仅限于 NET 4.0。在 NET 4.5 上不会引发任何异常。
这是预期的行为吗?我该怎么办?
最佳答案
这是因为 Close 方法关闭了窗体并销毁了它的句柄,然后在没有句柄的 Closed 窗体中调用了 MessageBox,所以出现了错误消息。
我不明白您的目的,但您应该将 Close 之后的代码移出调用,或者将 Close 移到它们之后。例如:
Invoke(new Action(() => {
Hide();
MessageBox.Show("closed in invoke from another thread");
new Form1();
Close();
}));
编辑:
关于 Control.Invoke 的 MSDN 说明:
The Invoke method searches up the control's parent chain until it finds a control or form that has a window handle if the current control's underlying window handle does not exist yet. If no appropriate handle can be found, the Invoke method will throw an exception. Exceptions that are raised during the call will be propagated back to the caller.
关于c# - 从 Invoke 中关闭表单,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29916970/