我有大量的数据和窗体控制来从文件加载,当文件大小真的很大时,我必须使用进度条。
问题是,进度条有效,但在程序开始构建数据并将其加载到表单时会立即冻结。
那么,无论如何我能使它发挥作用吗?我使用后台工作者和进度条。
以下是一些代码:
private void openToolStripMenuItem_Click(object sender, EventArgs e)
{
try
{
listBox2.Items.Clear();
listBox3.Items.Clear();
dataGridView1.RowCount = 0;
progressBar1.Visible = true;
reading.Visible = true;
backgroundWorker1.RunWorkerAsync();
setLabels();
progressBar1.Visible = false;
reading.Visible = false;
}
}
private void backgroundWorker1_DoWork(object sender, DoWorkEventArgs e)
{
for (int i = 1; i <= 100; i++)
{
// Wait 100 milliseconds.
Thread.Sleep(100);
// Report progress.
backgroundWorker1.ReportProgress(i);
}
}
private void backgroundWorker1_ProgressChanged(object sender,
ProgressChangedEventArgs e)
{
// Change the value of the ProgressBar to the BackgroundWorker progress.
progressBar1.Value = e.ProgressPercentage;
// Set the text.
reading.Text += " at " + e.ProgressPercentage.ToString() + "%";
}
答案 0 :(得分:1)
您应该在单独的线程上执行加载工作,并让主线程处理更新UI。例如:
您可以通过以下文件启动工作人员:
bgWorker.RunWorkerAsync(object);
然后连接一个DoWork方法来执行长时间运行的任务,这是您向UI报告结果/进度条百分比的地方:
private void bgWorker_DoWork(object sender, DoWorkEventArgs e)
{
object myObject = (object)e.Argument;
bgWorker.ReportProgress(//YOUR FORMULA TO WORK OUT PERCENTAGE);
}
对ReportProgress
的调用会调用ProgressChanged
事件,您可以使用以下命令从后台线程安全地更新UI:
private void bgWorker_ProgressChanged(object sender, ProgressChangedEventArgs e)
{
progressBar.Value = e.ProgressPercentage;
}
答案 1 :(得分:0)
必须阻止您的UI线程更新。这样做吧
private void updateProgressBar(int percent)
{
if (ProgressBar.InvokeRequired)
{
updateProgressBarCallback cb = new updateProgressBarCallback(updateProgressBar);
this.Invoke(cb, new object[] { percent });
}
else
{
ProgressBar.Value = percent;
ProgressBar.Update();
ProgressBar.Refresh();
ProgressBar.Invalidate();
}
}