问题描述
我试图使用的BackgroundWorker
来做出提前进度。最终的目标是展示一个背景搜索的进步,但我首先要了解做一个简单的模拟进度条。这是代码:
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;
}
但是当我运行它,它会跳过对末端,而不会改变进度以任何方式。当我调试它一步一步,最后一步,我得到的就是 worker.ReportProgress(J);
,则控制返回给程序和 worker_RunWorkerCompleted
被调用。为什么呢?
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?
推荐答案
如果你想修改 UI内容
,你应该把 UI调度
呼叫。您不能从后台线程
修改UI对象。
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();
});
和
App.Current.Dispatcher.Invoke((Action)delegate()
{
Title = "Done";
});
这篇关于在WPF BackgroundWorker的更新进度的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!