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