开发者

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.


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


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


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

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜