首页 > 解决方案 > 为什么 ProgressBar 不显示当前值/不刷新?

问题描述

我使用以下代码:

    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();

            progressBar1.Value = 0;
            progressBar1.Step = 1;
            progressBar1.Maximum = 100;
        }

        private void button1_Click(object sender, EventArgs e)
        {
            for (int i = 0; i < 100; i++)
            {
                Thread.Sleep(100);
                progressBar1.PerformStep();
                label1.Text = (i + 1).ToString();
                this.Refresh();
            }
        }
    }

但是,即使在this.Refresh();进度条的值之后没有更新。只有标签更新。当标签已经显示 100 时,进度条还有更多的步骤要完成。

我做错了什么?
为什么进度条的值没有更新?
我应该怎么做正确?

标签: c#.netwinformsprogress-bar

解决方案


你在使用任务、异步、等待吗?这是winforms中的常见示例

IProgress

public void DoWork(IProgress<int> progress)
{
    // This method is executed in the context of
    // another thread 
    for (int j = 0; j < 100000; j++)
    {
        //DO something

        // Use progress to notify UI thread that progress has
        // changed
        if (progress != null)
            progress.Report((j + 1) * 100 / 100000);
    }
}

private async void button_Click(object sender, EventArgs e)
{
    progressBar.Maximum = 100;
    progressBar.Step = 1;

    var progress = new Progress<int>(v =>
    {
        // This lambda is executed in context of UI thread,
        // so it can safely update form controls
        progressBar.Value = v;
    });

    // Run operation in another thread
    await Task.Run(() => DoWork(progress));
}

推荐阅读