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.
Your UI thread is a single thread, not two threads. To get your UI to be responsive, you either have to put the work on another thread (generally with a BackgroundWorker), or tell the UI to repaint itself in the UI thread.
I always have to experiment when I do things like this, but the Control.Refresh method should do it:
http://msdn.microsoft.com/en-us/library/system.windows.forms.control.refresh.aspx