Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 516
toni Avatar asked Mar 22 '10 21:03

toni


1 Answers

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);
        }
    }
like image 125
Scott J Avatar answered Oct 19 '22 02:10

Scott J