Winforms: Cross-thread operation not valid.

Hi all,

I sometimes get this error when I forget that controls cannot be accessed across threads:

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

What many people do is this:

  1. private void UpdateLabel(string text)
  2. {
  3.     this.Invoke(new Action(() => this.someLabel.Text = text));
  4. }

This is not the right pattern. You don’t always HAVE to invoke. You are better off by checking if you have to invoke it on the underlying thread, and if not, just execute it directly. It’s all about correctness 🙂

The right pattern would be:

 

  1. private void UpdateLabel(string text)
  2. {
  3.     if(this.InvokeRequired)
  4.     {
  5.         this.Invoke(new Action(() => this.UpdateLabel(text)));
  6.         return;
  7.     }
  8.  
  9.     this.someLabel.Text = text;
  10. }

Use Control.InvokeRequired 🙂

Good luck

-Kristof