15

I have got this code which runs an .exe

string openEXE = @"C:\Users\marek\Documents\Visual Studio 2012\Projects\tours\tours\bin\Debug\netpokl.exe";
                 Process b = Process.Start(openEXE);
                 b.EnableRaisingEvents = true;
                 b.Exited += (netpokl_Closed);

And when it closes it calls method netpokl_Closed. The issue is when I insert into netpokl_Closed command - this.Close() this exception rises: Cross-thread operation not valid: Control accessed from a thread other than the thread it was created on

How can I fix it ? Thank you for your time and answers.

Marek
  • 3,555
  • 17
  • 74
  • 123

3 Answers3

46

You are getting the exception because you are trying to close the form from a thread other than on what it was created on. This is not allowed.

do it like this

this.Invoke((MethodInvoker) delegate
        {
            // close the form on the forms thread
            this.Close();
        });
Ehsan
  • 31,833
  • 6
  • 56
  • 65
1

When a thread other than the creating thread of a control tries to access one of that control's methods or properties, it often leads to unpredictable results. A common invalid thread activity is a call on the wrong thread that accesses the control's Handle property

Gets or sets a value indicating whether to catch calls on the wrong thread that access a control's Handle property when an application is being debugged.

have a look at

http://msdn.microsoft.com/en-us/library/system.windows.forms.control.checkforillegalcrossthreadcalls.aspx

Andrew
  • 218
  • 4
  • 18
-1

You can close your form using Delegate

      public delegate void CloseDelagate(); 

      Form1.Invoke(new CloseDelegate(Form2.Close));
Rohit
  • 10,056
  • 7
  • 50
  • 82