0

以下のコードでは、進行状況バーは for ループに従って表示されます。しかし、 for ループでは、 Filecount は変数であり、ファイルの数に依存することを意味します。以下のコードは、ファイル カウントが 5、10、20 のように 100 に割り切れる場合は正常に動作しますが、ファイル カウントが 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

丸めのため、整数100 / FileCountはおそらくあなたが望む結果を与えていません。

私は通常これを行います:

ReportProgress(100 * fileIndex / fileCount)

代わりに (fileIndex+1) が必要な場合もあれば、別の操作として最後に 100 を指定して明示的に呼び出したい場合もあります。また、時間のかかる操作の前後 (またはその両方) に ReportProgress を呼び出すかどうかも気にする必要があります。

于 2012-09-27T12:09:48.003 に答える
0

プログレス バーは、特に 100 で割り切れないステップ数を扱っている場合 (パーセンテージを使用している場合) は、常に近似値です。

進行状況を 100% に設定する行をループの最後に追加するだけで問題ありません。

于 2012-09-27T12:09:05.187 に答える