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