0

So I'm trying to increase the Progress bar inside a foreach loop based on the number of lines processed in a file but it doesn't seem to work, not sure why maybe my maths is off?

Example of code

var lines = File.ReadAllLines(file);
size = lines.Length;
int progress = 100 / size;

foreach (var line in lines){
      progressBar1.BeginInvoke((MethodInvoker)delegate () { 
             progressBar1.Value += progress; 
      });
}
Prince Vegeta
  • 719
  • 6
  • 21
R2-D2
  • 143
  • 1
  • 9
  • @Bahrom just a Thread wrapper – R2-D2 Jul 12 '19 at 06:18
  • What isn't working? – skolldev Jul 12 '19 at 06:18
  • @xdecdec the progress bar – R2-D2 Jul 12 '19 at 06:19
  • No your maths is not off, it should work with this calculation. Do it work if you use `progressBar1.Value += progress;` without the `BeginInvoke` – Presi Jul 12 '19 at 06:20
  • Make sure, if lines are read by `foreach` loop. try to console them – Guga Nemsitsveridze Jul 12 '19 at 06:20
  • Why is `progress` an `int`? – FCin Jul 12 '19 at 06:20
  • @FCin because Progress.Value is a integer – R2-D2 Jul 12 '19 at 06:21
  • @Presi wont work without a invoke due to progressbar being created in a seperate thread – R2-D2 Jul 12 '19 at 06:22
  • 1
    @MurrayFoxcroft I will read through, within a split second of skimming the question, I saw something that may work for my use. Thanks – R2-D2 Jul 12 '19 at 06:23
  • so what does change here? the amount of files alias `size`? you say " it doesn't seem to work" please be more precise. What is the actual outcome? – Mong Zhu Jul 12 '19 at 06:28
  • 1
    Managed to fix this by simply removing progress integer & applying progressBar1.maximum = size; & then setting progressBar1.Value += 1; – R2-D2 Jul 12 '19 at 06:29
  • why should the amount of lines change? – Mong Zhu Jul 12 '19 at 06:30
  • @MongZhu the amount of lines don't change, but the value of the progressbar should change each loop which is equal to the amount of lines. However by default progressbar is set to 100 & if the amount of lines exceed 100, therefore the loop exceeds 100 & then the value of progressbar will exceed 100 and throw a exception, along with showing a inaccurate progress. – R2-D2 Jul 12 '19 at 06:33
  • very nice, why isn't all this information inside your post. ;) next time it really should be. It makes all our lifes easier. And much easier to help you. Glad to hear that you solved your problem. Hint aside: if performing such calculations : `int progress = 100 / size;` don't forget the case where the line is empty and `size == 0`. Happy coding – Mong Zhu Jul 12 '19 at 06:37

0 Answers0