我正在做我的第一个WinForms应用程序,其中包含后台工作程序和进度条。当我运行我的代码时,它看起来像进度条被延迟,因为当执行RunWorkerCompleted的代码时,它的动画 - 接近100% - 没有完成。 (进度条填充几百毫秒。) 有没有办法让事情更加同步?
从用户的角度来看,我希望进度条在其他事情开始发生之前达到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;
}
}
答案 0 :(得分:0)
做一个简单的技巧,而不是解决UI线程同步问题。
只需在_RunWorkerCompleted
中将进度条设置为100%。
void backgroundWorker1_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
{
progressBar1.Value = 100;
Application.DoEvents();
ExecuteButton.Enabled = false;
}