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