views:

37

answers:

1

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?

+2  A: 

Yes - that will execute Load 10 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, run Load, then report progress when you process the data. Assuming that takes some time. If all the time is in Load, then...

Marc Gravell
Thanks, after spending a lot of time. I used marquee as you told. But is there any way i can use CountTotal and CountLoaded to report progress in progress bar?
LifeH2O
@LifeJ20 - if there is an event or similar that fires after saving, maybe.
Marc Gravell
Can i make another BackgroudWorker that monitors Count.Loaded
LifeH2O
@LifeH20 - *possibly*, but then you are in a whole complex area of cross-theading data. Very tricky to get right.
Marc Gravell