问题描述
我正在做我的第一个WinForms应用程序,该应用程序具有后台工作程序和进度条.当我运行我的代码时,进度条似乎被延迟了,因为当执行RunWorkerCompleted的代码时,它的动画-接近100%-尚未完成. (填充进度条需要几百毫秒.)有没有办法使事情更加同步?
I'm doing my first WinForms application featuring a background worker and progress bar. When I run my code it looks like the progress bar is delayed, because its animation -- approaching 100% -- is not completed when the code for the RunWorkerCompleted is executed. (A few hundred milliseconds the progress bar is filled.)Is there a way to make things more synchronized?
从用户的角度来看,我希望进度条能在其他事情开始发生之前达到100%.
From a user perspective I'm expecting the progress bar to reach 100% before other things start to happen.
componentList.Count通常在5到15之间,这意味着进度动画每个增量大约会跳10-20%.
componentList.Count, below, is usually 5-15, meaning the progress animation jumps roughly 10-20% each increment.
我的代码:
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;
}
我当前的解决方法,给人以同时性的印象:
My current workaround, giving the impression of simultaneousness:
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 progressbar动画?"中建议的技巧.通过使用现有的实现,然后添加以下逻辑,我设法解决了问题:
Using the trick suggested in the question "Disabling .NET progressbar animation when changing value?" I managed to solve my problem by using the existing implementation and then adding the following logic:
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;
}
}
推荐答案
做一个简单的技巧,而不是解决UI线程同步问题.只需在_RunWorkerCompleted
中将进度条设置为100%.
Do a simple trick, instead of solving the UI thread synchronization problem.Simply set progress bar to 100% in _RunWorkerCompleted
.
void backgroundWorker1_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
{
progressBar1.Value = 100;
Application.DoEvents();
ExecuteButton.Enabled = false;
}
这篇关于在进度条达到100%之前触发RunWorkerCompleted的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!