Update progress bar from for loop

2020-04-10 03:49发布

问题:

I am processing some xml files in for loop and according to the number of files has been processed I want to show the progress bar. Suppose there are 100 files in directory and files are processing one by one in loop and I want to update the progress bar according to the current count of the for loop.
Please suggest..

回答1:

You should use BackgroundWorker combined with a ProgressBar control. Here is a simple example.



回答2:

Take a look at BackgroundWorker class, particularly, at ProgressChanged event.



回答3:

Process the 100 files using a Background Worker, call ReportProgress every iteration, hook on to the Process changed event of the backgroundworker and update a progressbar accordingly.

You can check out this tutorial for details.



回答4:

for(int i=1;i<linecount;i++)
{
 progressBar1.Value = i * progressBar1.Maximum / linecount;  //show process bar counts
 LabelTotal.Text = i.ToString() + " of " + linecount; //show number of count in lable
 int presentage = (i * 100) / linecount;
 LabelPresentage.Text = presentage.ToString() + " %"; //show precentage in lable
 Application.DoEvents(); keep form active in every loop
}