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

时间:2012-11-11 15:58:22

标签: c# multithreading backgroundworker

我正在尝试使用BackgroundWorker进行进度条前进。最终目标是显示后台搜索的进度,但我首先想要通过简单的模拟来了解进度条。这是代码:

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

但是当我运行它时,它会直接跳到最后,而不会以任何方式改变进度条。当我逐步调试它时,我到达的最后一步是worker.ReportProgress(j);,然后控制返回到程序并调用worker_RunWorkerCompleted。为什么呢?

2 个答案:

答案 0 :(得分:1)

你忘了管理工人:

     worker.RunWorkerAsync();

答案 1 :(得分:1)

如果您尝试更改UI content,则应将呼叫置于UI Dispatcher。你can't modify UI objects from background thread。用这些替换你的行 -

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

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