Saturday, July 20, 2013

How To Fix Cross Threading Operation not Valid C#

While working on Windows Application in C#, you might have come to a situation where you need to use threading. and you might encounter a error as Cross Threading not valid

Cross-thread operation not valid: Control label2 accessed from a thready other than the thread it was created on
Basically I was trying to access a control which was created in other thread, and I'm on other thread, so that's why I got this error

To fix this error is quite simple

There is a property called CheckForIllegalCrossThreadCalls

This is a boolean property i.e. It can only support either true or false

You just need to set this value to false, and place it in your form load method 

   1:      private void button1_Click(object sender, EventArgs e)
   2:          {
   3:              Thread objthread = new Thread(new ThreadStart(myfunc));
   4:              objthread.Start();
   5:              CheckForIllegalCrossThreadCalls = false;
   6:          }
   8:          void myfunc()
   9:          {
  10:              label2.Text = "Text Changed";
  11:          } 


No comments:

Post a Comment