本文介绍了BackgroundWorker的将不报告进度的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我运行一个数据库长任务后台工作。我希望任务运行时显示进度条。不知怎的,后台工作人员会不报告任务的进度。
I have a background worker running a long database task. i want to show the progress bar while the task is running. Somehow the background worker won't report the progress of the task.
这是我有:
BackgroundWorker _bgwLoadClients;
_bgwLoadClients = new BackgroundWorker();
_bgwLoadClients.WorkerReportsProgress = true;
_bgwLoadClients.DoWork += new DoWorkEventHandler(_bgwLoadClients_DoWork);
_bgwLoadClients.RunWorkerCompleted += new RunWorkerCompletedEventHandler(_bgwLoadClients_RunWorkerCompleted);
_bgwLoadClients.ProgressChanged += new ProgressChangedEventHandler(_bgwLoadClients_ProgressChanged);
_bgwLoadClients.RunWorkerAsync(parms);
private void _bgwLoadClients_DoWork(object sender, DoWorkEventArgs e)
{
DataTable dt = getdate();
e.Result = dt;
}
void _bgwLoadClients_ProgressChanged(object sender, ProgressChangedEventArgs e)
{
progressBar1.Value = e.ProgressPercentage;
}
我在WPF中这样做,但我想这不会有所作为。
I am doing this in WPF, but i guess it won't make a difference.
在此先感谢
推荐答案
您需要向下打破你的DoWork方法为报告进度,然后调用ReportProgress。
You need to break your DoWork method down into reportable progress and then call ReportProgress.
举个例子如下:
private void Something_DoWork(object sender, DoWorkEventArgs e)
{
// If possible, establish how much there is to do
int totalSteps = EstablishWorkload();
for ( int i=0; i<totalSteps; i++)
{
// Do something...
// Report progress, hint: sender is your worker
(sender as BackgroundWorker).ReportProgress((int)(100/totalSteps)*i, null);
}
}
如果你的工作不能predetermined,尝试将自己的命中率:
If your work can't be predetermined, try adding your own percentages:
private void Something_DoWork(object sender, DoWorkEventArgs e)
{
// some work
(sender as BackgroundWorker).ReportProgress(25, null);
// some work
(sender as BackgroundWorker).ReportProgress(50, null);
// some work
(sender as BackgroundWorker).ReportProgress(60, null);
// some work
(sender as BackgroundWorker).ReportProgress(99, null);
}
这篇关于BackgroundWorker的将不报告进度的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!