Wednesday, July 16, 2008

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

This exception is thrown when you try to access control from thread other than the thread it was created on.
To access control and control properties use delegate. Its easy. Here is example for accessing Label control (label1) Text property.


delegate void updateLabelTextDelegate(string newText);
private void updateLabelText(string newText)
{
if (label1.InvokeRequired)
{
// this is worker thread
updateLabelTextDelegate del = new updateLabelTextDelegate(updateLabelText);
label1.Invoke(del, new object[] { newText });
}
else
{
// this is UI thread
label1.Text = newText;
}
}


Now whenever you want to change text of label you call method updateLabelText(newText). You can do the same for all other controls.

keys: gui multithreading, update from another thread, threading, cross-thread,