1

I'm getting a error in my code

Cross-thread operation not valid: Control '' accessed from a thread other than the thread it was created on.

I don't know why it is happening. Can someone explain this to me?

Oscar Mederos
  • 29,016
  • 22
  • 84
  • 124
Andrew
  • 11
  • 1

3 Answers3

2

That is hapening because you are accessing to a control in your Windows Form application from another thread.

Could you share your code?

Let's suppose you are accessing to a TextBox (which name is textBox1):

textBox1.Text = "Modified text"

Instead of doing that, you must do:

MethodInvoker m = () => { textBox1.Text = "Modified text"; };
if (InvokeRequired) {
    BeginInvoke(m);
}
else {
    m.Invoke();
}

Of course, that was a simple example. You can encapsulate the Invoking part in in a method so you don't repeat the same code over and over. Something like:

public void InvokeSafe(MethodInvoker m) {
    if (InvokeRequired) {
        BeginInvoke(m);
    }
    else {
        m.Invoke();
    }
}

so all you have do to is:

MethodInvoker m = () => { textBox1.Text = "Modified text"; };
InvokeSafe(m);
Oscar Mederos
  • 29,016
  • 22
  • 84
  • 124
0

Common reason is if you are trying to access data available for UI thread from your background thread. Verify that you are not accessing data across threads.

You need to post more details.

Sandeep G B
  • 3,957
  • 4
  • 26
  • 43
0

The message is quite clear. Cross-thread calls can make the application very unstable thats why it is not valid.

Here is some documentation how to solve this:

RvdK
  • 19,580
  • 4
  • 64
  • 107