Windows Forms: Progress Bar Updated using Background Worker

  • Thread starter Thread starter AngryKeanu
  • Start date Start date
A

AngryKeanu

Guest
FMain has a progress bar control, barProgress.

When a button is clicked on the form, a new BackgroundWorker is created, worker.

The worker's ProgressChangedEventHandler is wired up:

worker.WorkerReportsProgress = true;
worker.DoWork += new DoWorkEventHandler(Worker_DoWork);
worker.RunWorkerCompleted += new RunWorkerCompletedEventHandler(Worker_RunWorkerCompleted);
worker.ProgressChanged += new ProgressChangedEventHandler(Worker_ProgressChanged);


In Worker_DoWork we instantiate a class called Merger which has a method called Execute() which is called in Worker_DoWork immediately after the class is instantiated. We pass the worker object as a parameter to class' constructor so it will be able to call worker.ReportProgress within a for loop.


private void Worker_DoWork(object sender, DoWorkEventArgs e)
{
Credentials creds = (Credentials)e.Argument;

Merger m = new Merger(this.selectedProfile, creds, worker, chkSeparator.Checked);
m.UpdateAction += M_ActionUpdated;
m.Execute(); <-- This is where the for...loop is that calls worker.ReportProgress
}




However, the progress bar isn't updated until the very end and then it jumps to 100% rendering it useless.

Here is the code for Worker_ProgressChanged:

private void Worker_ProgressChanged(object sender, ProgressChangedEventArgs e)
{
if (barProgress.InvokeRequired)
{
this.barProgress.Invoke((MethodInvoker)delegate
{
barProgress.Value = e.ProgressPercentage;
});
}
}

Thanks in advance.

Continue reading...
 
Back
Top