【问题标题】:The RunWorkerCompleted is triggered before the progressbar reaches 100% [duplicate]在进度条达到 100% 之前触发 RunWorkerCompleted [重复]
【发布时间】:2016-01-02 20:37:11
【问题描述】:

我正在做我的第一个 WinForms 应用程序,它具有后台工作程序和进度条。当我运行我的代码时,进度条看起来像是延迟了,因为它的动画——接近 100%——在执行 RunWorkerCompleted 的代码时没有完成。 (几百毫秒的进度条被填满。) 有没有办法让事情更加同步?

从用户的角度来看,我希望进度条在其他事情开始发生之前达到 100%。

componentList.Count,如下,通常为 5-15,这意味着进度动画每次增加大约跳跃 10-20%。

我的代码:

    private void ExecuteButton_Click(object sender, EventArgs e)
    {
        ExecuteButton.Enabled = false;
        backgroundWorker1.RunWorkerAsync();
    }

    private void backgroundWorker1_DoWork(object sender, DoWorkEventArgs e)
    {
        int filesRun = 0;
        foreach(string file in componentList)
        {
            api.ExecuteInstructions(file);
            int progress = ++filesRun * 100 / componentList.Count;
            backgroundWorker1.ReportProgress(progress);
        }
    }

    private void backgroundWorker1_ProgressChanged(object sender, ProgressChangedEventArgs e)
    {
        progressBar1.Value = e.ProgressPercentage;
    }

    void backgroundWorker1_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
    {
        ExecuteButton.Enabled = true;
    }

我目前的解决方法,给人一种同时性的印象:

    private void backgroundWorker1_DoWork(object sender, DoWorkEventArgs e)
    {
        int filesRun = 0;
        foreach(string file in componentList)
        {
            api.ExecuteInstructions(file);
            int progress = ++filesRun * 100 / componentList.Count;
            if(progress == 100)
                progress--;

            backgroundWorker1.ReportProgress(progress);
        }

        Thread.Sleep(650); // cosmetic paus
        backgroundWorker1.ReportProgress(100);
    }

更新:

使用问题“更改值时禁用 .NET 进度条动画?”中建议的技巧?我设法通过使用现有实现然后添加以下逻辑来解决我的问题:

    private void backgroundWorker1_ProgressChanged(object sender, ProgressChangedEventArgs e)
    {
        progressBar1.Value = e.ProgressPercentage;

        if (e.ProgressPercentage == 100)
        {
            progressBar1.Value = 101;
            progressBar1.Maximum = 100;
            progressBar1.Value = 100;
        }
    }

【问题讨论】:

  • 是的,@IvanStoev,你是对的。感谢您帮助我朝着正确的方向前进。

标签: c# winforms progress-bar backgroundworker


【解决方案1】:

做一个简单的技巧,而不是解决 UI 线程同步问题。 只需在_RunWorkerCompleted 中将进度条设置为 100%。

void backgroundWorker1_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
{
  progressBar1.Value = 100;
  Application.DoEvents();
  ExecuteButton.Enabled = false;
}

【讨论】:

  • 遗憾的是,这并没有奏效。设置 progressBar1.Value = 100 仍然需要动画运行。更新 Value 属性只需要几个周期,达到 100% 是不够的。
猜你喜欢
  • 1970-01-01
  • 2014-06-22
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多