I'm writing the functionality for a particular part of a program which requires me to change the text of a number of labels on a window continuously until the user presses a button. I've created a thread to accomplish this, and quickly noticed that the runtime complains about cross-thread accessing of a label, giving the error message:
Cross-thread operation not valid: Control 'label2' accessed from a thread other than the thread it was created on.
I've since learned that accessing a System.Windows.Forms.Control
member in a thread other than the UI thread is not allowed. However, my question has to do with the following simplified code:
private void myThread(){
//'labels' is an array of all labels on my form
Label currLabel = labels[rand.Next(0, labels.Length)];
currLabel.BackColor = Color.Yellow; //This works with no complaint from the runtime
currLabel.Text = "Hello"; //This causes the previously-mentioned error
}
So, why am I able to change some properties of labels in a thread other than the UI thread, but others are just off-limits? Am I missing some larger concept here? Any help is appreciated.