c# - 从 Invoke 中关闭表单

标签 c# winforms exception invoke ui-thread

像这样从 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/

相关文章:

c# - NLog 自定义 LayoutRenderer - json : can't get working

c# - 如何将数据集绑定(bind)到具有显示和值成员的下拉列表/组合框

.net - <92FB64J> 是无效的 XML 标签吗?

android - AlertDialog 中的随机崩溃

c# - 如何将 null 变为 0

c# - 为 Crystal Reports 中的参数分配多个值

c# - 更新 ListBox 的 DisplayMember

c# - 停止执行,关闭窗体并返回调用者

python - 从 requests.exceptions.HTTPError 获取 HTTP 错误代码

c# - 字典中的 string.Trim()