I am using the below function to Close existing form and opening new form. I am getting the below error when the code tries to close the existing form
我使用以下函数来关闭现有表单并打开新表单。当代码尝试关闭现有表单时,我收到以下错误
Error :
{System.InvalidOperationException: Cross-thread operation not valid: Control 'Screensaver' accessed from a thread other than the thread it was created on.
{System.InvalidOperationException:跨线程操作无效:控制'屏幕保护程序'从其创建的线程以外的线程访问。
Code :
public static class Program
{
/// <summary>
/// The main entry point for the application.
/// </summary>
[STAThread]
static void Main()
{
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
StartThread();
Application.Run(new MyContext(new Screensaver()));
}
public class MyContext : ApplicationContext
{
static private Form curMain = null;
public MyContext(Form main)
{
MyContext.NewMainForm(main, false);
}
static public void NewMainForm(Form main, bool ClosePreviousMain)
{
try
{
if (main != null)
{
if (ClosePreviousMain & MyContext.curMain != null)
{
MyContext.curMain.FormClosed -= new FormClosedEventHandler(main_FormClosed);
MyContext.curMain.Close();
}
MyContext.curMain = main;
MyContext.curMain.FormClosed += new FormClosedEventHandler(main_FormClosed);
MyContext.curMain.Show();
}
}
catch (Exception ex)
{
ExceptionHandler.writeToLogFile(System.Environment.NewLine + "Message : " + ex.Message.ToString() + System.Environment.NewLine + "Stack : " + ex.StackTrace.ToString());
}
}
static private void main_FormClosed(object sender, FormClosedEventArgs e)
{
Application.Exit();
}
}
1 个解决方案
#1
I would guess that MyContext.curMain
refers to a form that was created on another thread than the one that you are currently executing on when trying to close it (the call StartThread();
and the exception message indicates that there is some threading going on). All attempts to execute any methods in MyContext.curMain
must be performed on the thread that it was created on. This is achieved by using Invoke
or BeginInvoke
, as such:
我猜想MyContext.curMain引用的是一个在另一个线程上创建的表单,而不是你当前正在执行的那个线程上尝试关闭它(调用StartThread();并且异常消息表明有一些线程正在进行)。所有在MyContext.curMain中执行任何方法的尝试都必须在创建它的线程上执行。这是通过使用Invoke或BeginInvoke实现的,如下所示:
MyContext.curMain.Invoke(new Action(MyContext.curMain.Close));
#1
I would guess that MyContext.curMain
refers to a form that was created on another thread than the one that you are currently executing on when trying to close it (the call StartThread();
and the exception message indicates that there is some threading going on). All attempts to execute any methods in MyContext.curMain
must be performed on the thread that it was created on. This is achieved by using Invoke
or BeginInvoke
, as such:
我猜想MyContext.curMain引用的是一个在另一个线程上创建的表单,而不是你当前正在执行的那个线程上尝试关闭它(调用StartThread();并且异常消息表明有一些线程正在进行)。所有在MyContext.curMain中执行任何方法的尝试都必须在创建它的线程上执行。这是通过使用Invoke或BeginInvoke实现的,如下所示:
MyContext.curMain.Invoke(new Action(MyContext.curMain.Close));