0

在下面的代码中,进度条根据 for 循环显示。但是在 for 循环中 Filecount 是可变的,这意味着它取决于文件的数量。当文件计数可分为 100(如 5、10、20)时,以下代码工作正常,但如果文件计数为 6、7、13,则即使 for 循环已完成,进度条也未显示完成。如果 Filecount 可以是任何数字并且进度条应该显示据称已校准并与 for 循环同步,那么逻辑应该是什么?请参考下面的代码 -

 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;

        }
    } 
4

2 回答 2

2

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).

于 2012-09-27T12:09:48.003 回答
0

无论如何,进度条始终是近似值,尤其是当您处理的步骤数不能很好地被 100 整除时(如​​果您使用百分比)。

只需在循环末尾添加一行,将进度设置为 100%,就可以了。

于 2012-09-27T12:09:05.187 回答