Update progressbar from a backgroundworker in WPF

匿名 (未验证) 提交于 2019-12-03 07:50:05

问题:

I'm trying to make a progressbar advance using a BackgroundWorker. The final goal is to show the progress of a background search, but I first want to get to know the progress bar by doing a simple simulation. This is the code:

    public MainWindow()     {         InitializeComponent();          worker = new BackgroundWorker(); // variable declared in the class         worker.WorkerReportsProgress = true;         worker.DoWork += new DoWorkEventHandler(worker_DoWork);         worker.ProgressChanged += new ProgressChangedEventHandler(backgroundWorker1_ProgressChanged);         worker.RunWorkerCompleted += worker_RunWorkerCompleted;     }      private void worker_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)     {         this.Title += " DONE";     }      private void worker_DoWork(object sender, DoWorkEventArgs e)     {         for(int j = 0; j <= 100; j++)         {             worker.ReportProgress(j);             Title += j.ToString();             Thread.Sleep(50);         }     }      void backgroundWorker1_ProgressChanged(object sender, ProgressChangedEventArgs e)     {         searchProgressBar.Value = e.ProgressPercentage;     } 

But when I run it, it skips right to the end, without altering the progressbar in any way. When I debug it step-by-step, the last step I get to is worker.ReportProgress(j);, then control returns to the program and worker_RunWorkerCompleted is called. Why?

回答1:

In case you trying to change the UI content, you should put the calls on UI Dispatcher. You can't modify UI objects from background thread. Replace your lines with these -

App.Current.Dispatcher.Invoke((Action)delegate()         {             Title += j.ToString();         }); 

and

App.Current.Dispatcher.Invoke((Action)delegate()         {             Title = "Done";         }); 


回答2:

You forgot to run the worker:

     worker.RunWorkerAsync(); 


易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!