Friday, October 28, 2011

Invalid cross-thread operation

When UI controls are accessed from thread other than the main thread ‘invalid cross thread operation’ exception will be thrown. The message may prompt as “Cross-thread operation not valid: Control 'label1' accessed from a thread other than the thread it was created on”.

It can be handled from any of following two solutions.

A. Control Invoke:

· Check if invoke required

· Invoke the control if required

private void button1_Click(object sender, EventArgs e)


Thread myThread = new Thread(



UpdateLabel("Hello New Label!");





int i = 0;

private void UpdateLabel(string text)



text = text + i;

if (this.label1.InvokeRequired)



UpdateLabel(text + " invoked");



this.label1.Text = text;


B. Using background worker:

Background worker can be used to avoid such exceptions especially when we have to report progress or report completion. The controls can be accessed in RunWorkerCompleted or ProgressChanged events. Controls like progress bar can be accessed in progress changed event to make the user feel progress is on while the operation is going on. RunWorkerCompleted can be used to update labels,textbox etc after operation completed. If UI controls accessed in DoWork event, it will throw cross thread exception.

backgroundWorker2.RunWorkerCompleted += (x, y) =>


this.label1.Text ="Set some text.";