rosscj2533
rosscj2533

Reputation: 9323

Why doesn't Win Forms application update label immediately?

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.

Upvotes: 0

Views: 4356

Answers (2)

Robert Harvey
Robert Harvey

Reputation: 180777

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

Upvotes: 5

Thomas
Thomas

Reputation: 8003

You're blocking the UI thread by performing the sleep operations, which causes no redraws to happen. If you would sleep on another thread and Invoke the Label updates on the UI thread, then it should work as expected.

Upvotes: 2

Related Questions