简体   繁体   中英

Update progressbar from a backgroundworker in WPF

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?

你忘了跑工人了:

     worker.RunWorkerAsync();

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM