我有一个涉及两个窗体的 Windows 窗体应用程序。子表单用于将数据导出到 CSV 文件,并使用后台工作程序写入文件。发生这种情况时,我隐藏了表格。 后台工作程序运行时父窗体仍然处于事件状态,因此即使后台工作程序正在写入文件,用户也可以退出应用程序。在父窗体上,我添加了一个 FormClosing 事件处理程序,以在后台工作程序仍在运行时提示用户。 我遇到的问题是访问父窗体中的后台 worker 。这是我尝试过的...
private void MainForm_FormClosing(object sender, FormClosingEventArgs e)
{
ExportForm eForm = new ExportForm(GridView, TableName, GridProgressBar, ProgressLabel);
if (eForm.PartWorker.IsBusy == true)
MessageBox.Show("Busy");
}
问题在于它正在创建子窗体的新实例,因此后台工作人员永远不会因为它的 IsBusy 属性为真。我怎样才能在我的父表单中访问这个后台工作人员,以便我可以检查这个条件是否成立。
这是 PartWorker BackgroundWorker 的代码...
#region PartWorker Events
void PartWorker_DoWork(object sender, DoWorkEventArgs e)
{
GetSwitch();
int batchNum = 0;
bool done = false;
ProgressLabel.Visible = true;
while (!done)
{
for (int i = 1; i <= 100; i++)
{
Thread.Sleep(100);
PartWorker.ReportProgress(i);
}
done = Export.ExportPartition(SaveFile, DataTable, 50000, batchNum++);
}
}
void PartWorker_ProgressChanged(object sender, ProgressChangedEventArgs e)
{
Progress.Style = ProgressBarStyle.Blocks;
Progress.Value = e.ProgressPercentage;
//May want to put the file name that is being written here.
ProgressLabel.Text = "Writing File: " + e.ProgressPercentage.ToString() +"% Complete";
}
void PartWorker_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
{
Progress.Value = 100;
ProgressLabel.Visible = false;
Progress.Visible = false;
MessageBox.Show("Files sucessfully created!", "Files Saved", MessageBoxButtons.OK, MessageBoxIcon.Information);
PartWorker.Dispose();
this.Close();
}
#endregion
最佳答案
在主窗体中保留对子窗体的引用:
class MainForm : Form {
private ExportForm exportForm;
// assign exportForm wherever the child form is created
}
接下来,在您的 ExportForm
中,创建一个属性来指示表单仍在忙。
这是一种比访问其 BackgroundWorker
(阅读:封装)更好的方法。
class ExportForm : Form {
public bool IsBusy {
get { return this.PartWorker.IsBusy; }
}
}
然后通过访问新创建的属性在主窗体中进行检查:
void MainForm_FormClosing(object sender, FormClosingEventArgs e)
{
if (this.exportForm.IsBusy)
MessageBox.Show("Busy");
}
关于c# - 检查另一个表单中的线程是否仍在运行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7001256/