toni
toni

Reputation: 227

WPF Best point to update a progress bar from BackgroundWorker

I have a task that takes a long time to execute. In order to inform the user of the progress, I have a progress bar that I update inside DoWork.

Can anybody tell me if this 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'm unsure of the purpose of ReportProgress.

Upvotes: 8

Views: 8491

Answers (3)

Muad'Dib
Muad'Dib

Reputation: 29196

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));

Upvotes: 0

Scott J
Scott J

Reputation: 1331

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);
        }
    }

Upvotes: 10

Taylor Leese
Taylor Leese

Reputation: 52292

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 += ... ;

Upvotes: 0

Related Questions