且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

从非UI线程更新windows窗体上的标签?

更新时间:2023-01-13 09:54:40

标签的内容只能从UI线程中更改。使用 Invoke 方法在具有正确文本的UI线程上执行回调

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


I've been trying for 2 days to do this. I've looked at tons of *** 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!

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; });