AustinC AustinC - 1 year ago 77
C# Question

Changing Label properties in a thread

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

Answer Source

UI Components can only be accessed on the Main UI Thread. Therefore, as Multi-threading behaves, is creating a new thread on your system. By doing so, the Main UI's thread is not blocked. That being said, if you want to access the Controls, you need to call Invoke or BeginInvoke Methods, depending on the condition


Label1.BeginInvoke((Action) (() => { \\Multiple Line of codes here. }));

Also, check on these links:

Accessing UI Control from BackgroundWorker Thread - C#

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

Solve a cross-threading Exception in WinForms

ADDED NOTE: while it is possible not to use Invoke Methods at some point, it is still better safe than sorry. some may eventually throw such exceptions on runtime. depending on the situation the program is running at

Access to Windows Forms controls is not inherently thread safe. If you have two or more threads manipulating the state of a control, it is possible to force the control into an inconsistent state. Other thread-related bugs are possible, such as race conditions and deadlocks. It is important to make sure that access to your controls is performed in a thread-safe way.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download