Home > database >  How to report progress by percentages in backgroundworker dowork event?
How to report progress by percentages in backgroundworker dowork event?

Time:08-16

private void Bgw_DoWork(object sender, DoWorkEventArgs e)
        {
            BackgroundWorker worker = sender as BackgroundWorker;

            var filesl = GetFiles(@"D:\", "*.*").ToList();
            for(int i = 0; i < filesl.Count; i  )
            {
                FileInfo info = new FileInfo(filesl[i]);
                if (File.Exists(info.FullName))
                {
                    dic.Add(filesl[i], info.Length);
                }
                int progress = (int)(((float)(i   1) / filesl.Count) * 100);
                worker.ReportProgress(progress, filesl[i]);

                Thread.Sleep(100);
            }
        }

it's reporting fine the items in the list in the worker.ReportProgress but the variable int progress value is all the time 0. in this case there are almost 40000 files in filesl.

CodePudding user response:

It's perfectly correct. Due to the amount of files the variable will return "0" (0%) until it reaches at least 400 files, which then the calculation would return "1" (1%). If you do this calculation more precisely (without converting to INT) you will see that the percentage is fractional, 0.005%, 0.0075%...

  • Related