我正在尝试使用BG Worker增加进度条。 我目前正在使用2个BG工作人员,一个用于将数据添加到数据库中,另一个用于进度条。数据库上传工作正常,但进度条不是。
代码:
BackgroundWorker bg2 = new BackgroundWorker();
bg2.DoWork +=new DoWorkEventHandler(bg2_DoWork);
bg2.RunWorkerAsync();
void bg2_DoWork(object sender, DoWorkEventArgs e)
{
while (bg1.IsBusy)
DrawWellPlate.pbar.Increment(1)
}
它引用的bg1是数据库上传线程,而pbar显然是进度条。
感谢。
答案 0 :(得分:4)
你应该做这样的事情 其中totalProgress将显示在progressBar中,doWork不在UI线程中执行,这是BackgroundWorker的目的
BackgroundWorker bg2 = new BackgroundWorker();
bg2.DoWork +=new DoWorkEventHandler(bg2_DoWork);
.ProgressChanged += new ProgressChangedEventHandler(bg2_ProgressChanged)
bg2.RunWorkerAsync();
void bg2_DoWork(object sender, DoWorkEventArgs e)
{
while (bg1.IsBusy)
worker.ReportProgress(totalProgress);
}
private void bg2_ProgressChanged(object sender,
ProgressChangedEventArgs e)
{
DrawWellPlate.pbar.Value = e.ProgressPercentage;
}
有关详细信息,请参阅this
答案 1 :(得分:2)
问题是bg1在运行其DoWork方法时会始终报告它正忙。
你应该只使用一个后台工作者,并在其工作方法中使用这样的东西(伪代码):
void bg1_DoWork(object sender, DoWorkEventArgs e)
{
while(got_stuff_to_add_to_the_database)
{
//do *some* of the work
AddABit()
//Update the progress - 5% at a time?
totalProgress += 5
//update the progress bar
ReportProgress(totalProgress)
if(finished)
{
got_stuff_to_add_to_the_database = false;
}
}
}