【问题标题】:Progress bar calibration synchronized with for loop与 for 循环同步的进度条校准
【发布时间】:2012-09-27 20:09:48
【问题描述】:

在下面的代码中,进度条是根据 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;

        }
    } 

【问题讨论】:

  • 完成后将进度条设置为100。

标签: c# winforms progress-bar


【解决方案1】:

由于四舍五入,您的整数 100 / FileCount 可能没有给您想要的结果。

我通常这样做:

ReportProgress(100 * fileIndex / fileCount)

您可能想要 (fileIndex+1) 代替,或者您可能想要在末尾显式调用 100 作为单独的操作。您可能还关心在耗时操作之前还是之后(或两者)调用 ReportProgress。

【讨论】:

    【解决方案2】:

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

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-01-18
      • 2020-06-14
      • 2016-11-24
      相关资源
      最近更新 更多