In almost all tutorials of BackgroundWorker the reportProgress event is handled like this (this example is from MSDN http://msdn.microsoft.com/en-us/library/cc221403(VS.95).aspx)
private void bw_DoWork(object sender, DoWorkEventArgs e)
{
BackgroundWorker worker = sender as BackgroundWorker;
for (int i = 1; (i <= 10); i++)
{
if ((worker.CancellationPending == true))
{
e.Cancel = true;
break;
}
else
{
// Perform a time consuming operation and report progress.
// _results.Load() downloads XML and save the data to database
System.Threading.Thread.Sleep(500);
worker.ReportProgress((i * 10));
}
}
}
My function downloads XML and save it to database after parsing. I called this function below “// Perform a time consuming operation and report progress.” But won’t my function run 10 times?
Later i modified Load() adding to variables CountTotal (total number of results) and CountLoaded (number of results saved, it changes as the function progress).
private void bw_DoWork(object sender, DoWorkEventArgs e)
{
BackgroundWorker worker = sender as BackgroundWorker;
for (int i = 1; (i <= 10); i++)
{
if ((worker.CancellationPending == true))
{
e.Cancel = true;
break;
}
else
{
// Perform a time consuming operation and report progress.
_results.Load() downloads XML and save the data to database
worker.ReportProgress((_results.CountLoaded * 10)); //i did something like this
}
}
}
The problem is that worker.ReportProgress executes after the completion of _results.Load(). How to solve this problem? Are the given examples on internet really bad because they are suggesting to call the function in a loop, or I got them wrong?
Yes – that will execute
Load10 times. The intent in that example is to illustrate usage when you can estimate the overall workload, or report meaningful progress. They are just trying to simulate “some work” with progress indication.If you can’t do that, then just run it async (via
BackgroundWorker) but show a scrolling infinite marquee or similar. Don’t do it 10 times ;p Alternatively, runLoad, then report progress when you process the data. Assuming that takes some time. If all the time is inLoad, then…