我有一个加载文件的方法。有时需要很长时间,所以我想向用户显示一个进度条窗口,他可以使用它最小化整个应用程序或取消进度。
我已经阅读了一堆关于 BackgroundWorkers 和 ProgressBars 的教程,但是当 ProgressBar 处于其他某种形式时,这些都没有涵盖这种情况。我不知道我应该什么时候打开新表单以及如何访问那里的进度条。
到目前为止,我已经尝试过:
主窗体:
private void addFolderToolStripMenuItem_Click(object sender, EventArgs e)
{
ctlFolderSelectDialog dlg = new ctlFolderSelectDialog();
if (dlg.ShowDialog() == DialogResult.OK)
{
BackgroundWorker.RunWorkerAsync(dlg); // to pass some variables from ctlFolderSelectDialog
}
}
private void BackgroundWorker_DoWork(object sender, DoWorkEventArgs e)
{
Form_Dialogs.ProgressDialog progressDialog = new Form_Dialogs.ProgressDialog();
progressDialog.ShowDialog(); // open the progress dialog window
myClass.loadFiles((ctlFolderSelectDialog)e.Argument); // THE WORK
progressDialog.Close(); // close the progress window - in here?
}
我的课:
public void loadFiles(ctlFolderSelectDialog dlg)
{
...
files.Count() // somehow report this preliminary number of files to ProgressBar window - to set ProgressBar1.Maximum value
...
foreach (file in files)
{
loadFile();
... // here I should somehow udpate the progressBar on the other window - performStep()
}
}
进度对话框:
private void ProgressDialog_Load(object sender, EventArgs e)
{
progressBar1.Value = 0;
progressBar1.Maximum = 100; // how to get this value from myClass function? Pass in ProgressDialog contructor?
progressBar1.Step = 1;
}
public void UpdateProgress(int progress)
{
progressBar1.PerformStep();
}