Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Progress bar and file loading

I have a large text file containing lots of lines of data. In my application I open this file, read each line by matching a regular expression and display it in a Datagridview. The total number of rows generated are around 2000(Sometimes even more, so pretty huge).

So for all this operations it takes fairly large amount of time. So I moved this code into another thread using background worker and everything is fine except that I want to show the loading status in a progress bar where I am failing.

I have used FileInfo class to get the file length and then gave this value to the Progressbar.Maximum. Seems not the right approach because a test file containing "3" lines returned a file length of "305". I donot understand how much step interval I should be giving this way.

Code sample:

FileInfo ff = new FileInfo(openFileDialog1.FileName);
int fsize= Convert.ToInt32(ff.Length);
int val=1;
pgbar_load.Invoke(new MethodInvoker(delegate { pgbar_load.Maximum = fsize; }));

and in the loop:

++val;
wk.ReportProgress(val);

and then:

private void bgwrkr_load_ProgressChanged(object sender, ProgressChangedEventArgs e)
{
   pgbar_load.Value = e.ProgressPercentage;
}

So two things I am looking for:

  1. Setting the maximum value for the progress bar.
  2. Setting the step index correctly.

Please suggest me a way to move forward.

like image 326
Cdeez Avatar asked Sep 16 '12 05:09

Cdeez


1 Answers

Keep Progressbar.Maximum at 100. Then track your read data in a int variable. Run a loop on the UI thread (you can use timer to do this), that sets the value of progress bar percent by checking your read bytes. E.g. assume you store your read bytes in int totalRead; and int totalFileSize contains size of your file.

myProgressBar.Value = Convert.ToInt32(Math.Ceil(100d * totalRead/totalFileSize));

You can put this in your timer tick event handler. This will run the progress bar gradually to 100%. When file read is complete, disable the timer.

like image 161
loopedcode Avatar answered Oct 19 '22 20:10

loopedcode