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(

delegate()

{

UpdateLabel("Hello New Label!");

}

);

myThread.Start();

}

int i = 0;

private void UpdateLabel(string text)

{

i++;

text = text + i;

if (this.label1.InvokeRequired)

this.label1.Invoke((MethodInvoker)delegate()

{

UpdateLabel(text + " invoked");

});

else

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.";

};

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

{

Progressbar1.value=y.ProgressPercentage;

}

No comments:

Post a Comment