Tuesday, December 9, 2014

Progress bar for long running task in Parallel.ForEach

Progress bar for long running task in Parallel.ForEach

Please note to update the progress bar and update the counter in thread safe manner, the code is written into lock block.
Lock keyword is used to handle the threads to enter into critical section.

int counter, totalFiles;
private void StartJob_Click(object sender, EventArgs e)
{
 progressBar1.Maximum = 100;
 progressBar1.Step = 1;
 progressBar1.Value = 0;
 backgroundWorker1.RunWorkerAsync();           
 }

private void backgroundWorker1_DoWork(object sender, DoWorkEventArgs e)
{
 List files = GetFiles();
 totalFiles = files.Count;
 // Let say Reading Files and Stroing them into Database
 Object countLock = new Object();
 Parallel.ForEach(Files, file =>
 {
  ProcessFiles(file);
  lock (countLock)
  {
   counter++;
   i++;
   backgroundWorker1.ReportProgress((i * 100) / totalFiles);
  }
 });

}

private void ReportProgress(int value)
{
  progressBar1.Value = value;
 label1.Text = string.Format("{0} Files Processed from the total of {1}: Completed: {2}%", counter, totalFiles, value.ToString());
}

No comments:

Post a Comment