使用Invoke方法外螺纹关闭窗体 [英] Close a form from an external thread using the Invoke method
问题描述
我不得不从一个线程关闭窗体,我使用窗体的Invoke方法来调用Close()方法。
I have to close a Form from a thread and I am using the Invoke method of the Form for calling the Close() method.
的问题是,当收盘时,形式布置,我得到一个InvalidOperationExecption机智的消息调用或BeginInvoke可直到窗口句柄已创建不能在一个控件调用。
The problem is that when closing, the form is disposed and I get an InvalidOperationExecption wit the message "Invoke or BeginInvoke cannot be called on a control until the window handle has been created.".
我已经得到了步入中的关闭方法,但我不想与正常运行的可能错误调试的风险,只有当这个异常。
I have got this exception only when debugging with a "Step Into" in the Close method but I don't want to risk with a possible error on normal running.
这是一个示例代码重现它:
This is an example code to reproduce it:
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.
}
));
}
的形式设置在表单的自动生成的代码(我会喜欢不修改):
The form is disposed in the automatic generated code for the form (which I would like not to modify):
protected override void Dispose(bool disposing)
{
if (disposing && (components != null))
{
components.Dispose();
}
base.Dispose(disposing);
}
我将不胜感激,如果有人可以给我这个或另一种方式的解决方案。从另一个线程关闭窗体
I would appreciate it if someone could give me a solution for this or another way to close a form from another thread.
推荐答案
从任何其他线程可以执行这个(从.NET 2.0):
From any other thread you can execute this (from .NET 2.0) :
myform.Invoke((MethodInvoker)delegate() { myform.Close(); });
注意:如果您有误差调用或BeginInvoke的可直到窗口句柄已创建不能在一个控件调用
你必须做的是这样的:
Note : If you have error Invoke or BeginInvoke cannot be called on a control until the window handle has been created
you have to do like this :
if (InvokeRequired)
{
Invoke((MethodInvoker)delegate()
{
Close();
});
}
else
{
Close();
}
这篇关于使用Invoke方法外螺纹关闭窗体的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!