Why doesn't Win Forms application update label immediately?
Posted
by rosscj2533
on Stack Overflow
See other posts from Stack Overflow
or by rosscj2533
Published on 2010-05-22T17:59:37Z
Indexed on
2010/05/22
18:10 UTC
Read the original article
Hit count: 175
I am doing some experimenting with threads, and made a 'control' method to compare against where all the processing happens in the UI thread. It should run a method, which will update a label at the end. This method runs four times, but the labels are not updated until all 4 have completed. I expected one label to get updated about every 2 seconds. Here's the code:
private void button1_Click(object sender, EventArgs e)
{
Stopwatch watch = new Stopwatch();
watch.Start();
UIThreadMethod(lblOne);
UIThreadMethod(lblTwo);
UIThreadMethod(lblThree);
UIThreadMethod(lblFour);
watch.Stop();
lblTotal.Text = "Total Time (ms): " + watch.ElapsedMilliseconds.ToString();
}
private void UIThreadMethod(Label label)
{
Stopwatch watch = new Stopwatch();
watch.Start();
for (int i = 0; i < 10; i++)
{
Thread.Sleep(200);
}
watch.Stop();
// this doesn't set text right away
label.Text = "Done, Time taken (ms): " + watch.ElapsedMilliseconds;
}
Maybe I'm just missing something basic, but I'm stuck. Any ideas? Thanks.
© Stack Overflow or respective owner