Update label on windows form from non-UI thread?

2019-07-18 17:00发布

问题:

I've been trying for 2 days to do this. I've looked at tons of stackoverflow answers and tried all of them, i still get the same problem.

I have a label on a windows form. The only code on this windows form is:

var thread1 = new Thread(new ThreadStart(Censored.Signup));
thread1.Start();

Now, on the windows form I also have a label. It's name is "createdLabel"

On the thread1 (Censored.Signup) i talked about a minute ago, I have the following code (along w/ other code that actually makes up the program, irrelevant):

int created = 0;
for (int i = 0; i < 10; i++)
{

   created++;
   createdLabel.Text = (string.Format("Created: [{0}]", created));
}

All i want is to update the label (createdLabel, on the form) with the info (created) from the worker thread (Censored.Signup).

for example (">" represents what happens next/after):
label1 = 0 > loop in Censored.Signup runs through and updates label on form > label1 = 1

I tried to make this as "explain like i'm 5" as possible to try and be really clear, but if anyone is confused and needs anything cleared up just let me know. Any help would be greatly appreciated. Thanks!

回答1:

The contents of the label can only be changed from the UI thread. Use the Invoke method to execute a call back on the UI thread that has the correct text

string text = string.Format("Created: [{0}]", created);
createdLabel.Invoke((Action)delegate { createdLabel.Text = text; });