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.
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();
}
}
I would guess that
MyContext.curMainrefers to a form that was created on another thread than the one that you are currently executing on when trying to close it (the callStartThread();and the exception message indicates that there is some threading going on). All attempts to execute any methods inMyContext.curMainmust be performed on the thread that it was created on. This is achieved by usingInvokeorBeginInvoke, as such: