我必须从一个线程中关闭一个表单,我正在使用该表单的 Invoke 方法来调用 Close() 方法。
问题是当关闭时,表单被处理,我得到一个 InvalidOperationExecption 机智消息“在创建窗口句柄之前无法在控件上调用 Invoke 或 BeginInvoke。”。
只有在 Close 方法中使用“Step Into”进行调试时我才会遇到此异常,但我不想在正常运行时冒可能出错的风险。
这是重现它的示例代码:
private void Form1_Load(object sender, EventArgs e)
{
Thread thread = new Thread(CloseForm);
thread.Start();
}
private void CloseForm()
{
this.Invoke(new EventHandler(
delegate
{
Close(); // Entering with a "Step Into" here it crashes.
}
));
}
表单在自动生成的表单代码中处理(我不想修改):
protected override void Dispose(bool disposing)
{
if (disposing && (components != null))
{
components.Dispose();
}
base.Dispose(disposing);
}
如果有人能给我一个解决方案或其他方法来关闭来自另一个线程的表单,我将不胜感激。
最佳答案
使用这个方法:
// Inspired from: http://stackoverflow.com/a/12179408/1529139
public static void InvokeIfRequired(Control control, MethodInvoker action)
{
if (control.IsDisposed)
{
return;
}
if (control.InvokeRequired)
{
try
{
control.Invoke(action);
}
catch (ObjectDisposedException) { }
catch (InvalidOperationException e)
{
// Intercept only invokation errors (a bit tricky)
if (!e.Message.Contains("Invoke"))
{
throw e;
}
}
}
else
{
action();
}
}
使用示例:
Functions.InvokeIfRequired(anyControl, (MethodInvoker)delegate()
{
// UI stuffs
});
关于c# - 使用 Invoke 方法从外部线程关闭窗体,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10084691/