Reputation: 453
In the code below progress bar is showing according to the for loop. But in the for loop the Filecount is variable means it depends on the number of file. Below code is working fine when the file count is dividable to 100 like 5,10,20 but if the Filecount is 6,7,13 then the progress bar is not showing completed even though the for loop has finished. What should be the logic if the Filecount could be any number and progress bar should show purportedly calibrated and in synch with for loop? Please refer Code below -
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
Shown += new EventHandler(Form1_Shown);
// To report progress from the background worker we need to set this property
backgroundWorker1.WorkerReportsProgress = true;
// This event will be raised on the worker thread when the worker starts
backgroundWorker1.DoWork += new DoWorkEventHandler(backgroundWorker1_DoWork);
// This event will be raised when we call ReportProgress
backgroundWorker1.ProgressChanged += new ProgressChangedEventHandler(backgroundWorker1_ProgressChanged);
}
void Form1_Shown(object sender, EventArgs e)
{
// Start the background worker
backgroundWorker1.RunWorkerAsync();
}
// On worker thread so do our thing!
void backgroundWorker1_DoWork(object sender, DoWorkEventArgs e)
{
int temp = 0;
int Filecount = 7;
// Your background task goes here
for (int i = 0; i < Filecount; i++)
{
int Progress = 100 / Filecount;
temp = temp + Progress;
// Report progress to 'UI' thread
backgroundWorker1.ReportProgress(temp);
// Simulate long task
System.Threading.Thread.Sleep(100);
}
}
// Back on the 'UI' thread so we can update the progress bar
void backgroundWorker1_ProgressChanged(object sender, ProgressChangedEventArgs e)
{
// The progress percentage is a property of e
progressBar1.Value = e.ProgressPercentage;
}
}
Upvotes: 0
Views: 869
Reputation: 39500
Your integer 100 / FileCount
probably isn't giving you the result you want, because of rounding.
I usually do this:
ReportProgress(100 * fileIndex / fileCount)
You might want (fileIndex+1) instead or you might want to call it explicitly with 100 at the end as a separate operation. You might also care about whether you call ReportProgress before or after the time-consuming operation (or both).
Upvotes: 2
Reputation: 33139
Progress bars are always approximations anyway, especially if you are dealing with a number of steps that is not nicely divisable by 100 (if you're using percentages).
Simply add a line at the end of your loop that sets the progress to 100% and you'll be fine.
Upvotes: 0