views:

552

answers:

3

I have a task that takes a long time executing. In order to inform about the progress to the user I have a progress bar that I update inside DoWork but I would like anybody tells me if it is the best way to update the progress bar. I have heard that there is a ReportProgress event handler but I am confused because I don't know what is the utility of the ReportProgress.

A: 

ReportProgress is what you would use to update the progress of your task, including things like the UI--in your case, a proggress bar.

You should check out the MSDN docs, located here.

basically, you create a handler for the ReportProgress event, then in your DoWorkEventHandler, you call the ReportProgress like so:

worker.ReportProgress((i * 10));
Muad'Dib
Ok! thanks, so I can call ReportProgress and it will raise ProgressChanged event as Maurizio says. Then Inside progressChanged event I can update any control of my UI that I want, for example, progressbar, label, textblock, ... with no need to call Dispatcher.Invoke. Am I right?Thanks.
toni
that is correct!
Muad'Dib
A: 

The ProgressChanged event is what you are looking for. However, make sure you create the BackgroundWorker like below so it actually raises this event when ReportProgress is called.

BackgroundWorker bw = new BackgroundWorker() { WorkerReportsProgress = true };
bw.ProgressChanged += ... ;
Taylor Leese
+1  A: 

Since the Background worker works in a separate thread, you'll run into problems if you try to access UI objects. Calling the ReportProgress method on the worker from inside the DoWork handler raises the ProgressChanged event. That event should be handled in the UI thread so as to easily access the control.

        BackgroundWorker worker = new BackgroundWorker();
        worker.DoWork += DoWorkHandler;
        worker.WorkerReportsProgress = true;
        worker.ProgressChanged += (s, e) => 
            { myProgressBar.Value = e.ProgressPercentage; };

        worker.RunWorkerAsync();

...

    public void DoWorkHandler(object sender, DoWorkEventArgs e)
    {
        BackgroundWorker worker = sender as BackgroundWorker;

        while (working)
        {
            // Do Stuff

            worker.ReportProgress(progressPercentage);
        }
    }
Scott J