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?