为什么我的后台工作程序不能用于进度条(默认情况下将可见性设置为false。)。
我正在尝试在后台设置进度条。当用户单击“确定”按钮时,我启动计时器并使进度条可见。 并运行backgroundWorker.RunWorkerAsync();在backgroundWorker_RunWorkerCompleted中,我将进度条的可见性设置为false。
问题是它只显示进度条但不显示进度。
我的代码在这里:
private void btnOk_Click(object sender, EventArgs e)
{
timer.Start();
progressBar.Visible = true;
backgroundWorker.RunWorkerAsync();
doSomeWork();
}
private void backgroundWorker_DoWork(object sender, DoWorkEventArgs e)
{
}
private void backgroundWorker_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
{
timer.Stop();
progressBar.Visible = false;
}
private void timer_Tick(object sender, EventArgs e)
{
MessageBox.Show("called");
if (progressBar.Value == progressBar.Maximum)
{
progressBar.Value = progressBar.Minimum;
return;
}
progressBar.PerformStep();
}
private void backgroundWorker_ProgressChanged(object sender, ProgressChangedEventArgs e)
{
progressBar.Value = e.ProgressPercentage;
}
为什么它不会在进度条中显示进度?它有什么不对吗?
答案 0 :(得分:2)
您的backgroundWorker_DoWork
没有做任何事情。在doSomeWork
事件中移动DoWork
。您需要将ReportProgress
设置为true
。
private void btnOk_Click(object sender, EventArgs e)
{
timer.Start();
progressBar.Visible = true;
backgroundWorker.ReportsProgress = true;
backgroundWorker.RunWorkerAsync();
}
private void backgroundWorker_DoWork(object sender, DoWorkEventArgs e)
{
doSomeWork();
}
private void doSomeWork()
{
//do what you want here..
backgroundWorker.ReportProgress(yourprogresspercentagenumber);
//do what you want again..
backgroundWorker.ReportProgress(yourprogresspercentagenumber);
}
答案 1 :(得分:2)
你在这里混合了两个概念。请确定您是否要使用计时器或后台工作人员。
没有任何反应的原因是您的backgroundWorker_DoWork
没有。因此,后台工作人员立即完成并调用backgroundWorker_RunWorkerCompleted
,再次停止计时器。
backgroundWorker_ProgressChanged
,因为只有在您致电backgroundWorker.ReportProgress()
(backgroundWorker.ReportsProgress
设置为true
)时才会提出该事件。
我认为您在doSomeWork()
中所做的工作应该在backgroundWorker_DoWork
报告进度时完成。尝试这样的事情:
private void btnOk_Click(object sender, EventArgs e)
{
progressBar.Visible = true;
backgroundWorker.ReportsProgress = true;
backgroundWorker.RunWorkerAsync();
}
private void backgroundWorker_DoWork(object sender, DoWorkEventArgs e)
{
doALittleWork();
backgroundWorker.ReportProgress(10, null);
doMoreWork();
backgroundWorker.ReportProgress(20, null);
//...
doLastWork();
backgroundWorker.ReportProgress(100, null);
}
private void backgroundWorker_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
{
progressBar.Visible = false;
}
private void backgroundWorker_ProgressChanged(object sender, ProgressChangedEventArgs e)
{
progressBar.Value = e.ProgressPercentage;
}
这应该做你想要的。在那种情况下不需要计时器。