为什么Win Forms应用程序不会立即更新标签?

ros*_*533 0 c# winforms

我正在做一些线程试验,并制作了一个"控制"方法来比较UI线程中发生的所有处理.它应该运行一个方法,它将在最后更新标签.此方法运行四次,但标签在完成所有4个之前不会更新.我期望一个标签每2秒更新一次.这是代码:

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;
}
Run Code Online (Sandbox Code Playgroud)

也许我只是缺少一些基本的东西,但我被困住了.有任何想法吗?谢谢.

Rob*_*vey 5

您的UI线程是单个线程,而不是两个线程.要让您的UI响应,您必须将工作放在另一个线程(通常使用BackgroundWorker),或者告诉UI在UI线程中重新绘制自己.

当我做这样的事情时,我总是要做实验,但是Control.Refresh方法应该这样做:

http://msdn.microsoft.com/en-us/library/system.windows.forms.control.refresh.aspx