简体   繁体   English

从WPF中的后台工作者更新进度条

[英]Update progressbar from a backgroundworker in WPF

I'm trying to make a progressbar advance using a BackgroundWorker . 我正在尝试使用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); 当我逐步调试它时,我得到的最后一步是worker.ReportProgress(j); , then control returns to the program and worker_RunWorkerCompleted is called. ,然后控制返回程序并worker_RunWorkerCompleted Why? 为什么?

你忘了跑工人了:

     worker.RunWorkerAsync();

In case you trying to change the UI content , you should put the calls on UI Dispatcher . 如果您尝试更改UI content ,则应将调用放在UI Dispatcher You can't modify UI objects from background thread . 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";
        });

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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