progressBar1.Visible = true;
progressBar1.Maximum = dt.Rows.Count;
if (dt.Rows.Count > 0)
{
for (int i = 0; i < dt.Rows.Count; i++)
{
-----
----
-----
progressBar1.Value = i;
if (progressBar1.Value == progressBar1.Maximum - 1)
{
MessageBox.Show("Task completed");
progressBar1.Visible = false;
}
}
}
答案 0 :(得分:2)
for循环冻结了你的UI线程,这就是为什么应用程序冻结,因为当你在for循环中工作时无法重绘UI。我建议将你的工作卸载到另一个线程,然后使用后台Worker:
BackgroundWorker worker = new BackgroundWorker();
worker.DoWork += (worker, result) =>
{
int progress = 0;
//DTRowCount CANNOT be anything UI based here
// this thread cannot interact with the UI
if (DTRowCount > 0)
{
for (int i = 0; i < dt.Rows.Count; i++)
{
progress = i;
-----
---- //do some operation, DO NOT INTERACT WITH THE UI
-----
(worker as BackgroundWorker).ReportProgress(progress);
}
}
};
worker.ProgressChanged += (s,e) =>
{
//here we can update the UI
progressBar1.Value = e.ProgressPercentage
};
worker.RunWorkerCompleted += (s, e) =>
{
MessageBox.Show("Task completed");
progressBar1.Visible = false;
};
worker.RunWorkAsync();
我的目标是将此循环卸载到另一个线程中,这将允许您的应用程序继续使用Windows消息泵并保持对用户的响应。工作者循环并在另一个线程上执行它需要的东西,这不能与UI或WindowForms(我假设你的使用)交互将抛出和错误。
根据worker.ProgressChanged
事件,Worker返回主线程和进度报告,从这里您可以访问UI并更改进度条值。
当工作人员完成后,它将回调到WorkerThread.RunWorkerCompleted
并再次从此处操作UI。
编辑:Code,WorkerThread.RunWorkerCompleted to worker.RunWorkerCompleted