以下のコードでは、進行状況バーは 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;
}
}