3

我正在尝试使用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调用。为什么?

4

2 回答 2

1

你忘了运行工人:

     worker.RunWorkerAsync();
于 2012-11-11T16:08:34.220 回答
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";
        });
于 2012-11-11T16:14:38.853 回答