[英]parent form closing invoke child form which has background worker in it
I try to achieve this: i have the main form, when user click the red cross on the top right to exit the application, it popup a progress bar form indicating the application is updating/saving information. 我尝试实现此目的:我有一个主窗体,当用户单击右上角的红叉以退出应用程序时,它会弹出一个进度栏窗体,指示该应用程序正在更新/保存信息。 After the background worker in the progress bar form finishes, it closes the progress bar form and close the main form as well. 进度栏窗体中的后台工作人员完成后,将关闭进度栏窗体并关闭主窗体。 the problem i have is, it closes the main from first without even running the background worker. 我的问题是,它从一开始就关闭了主电源,甚至没有运行后台程序。 how to fix this? 如何解决这个问题? i tried to use e.cancel= true it just gave my dead loop. 我试图使用e.cancel = true,它给了我死循环。
here is my main form: 这是我的主要形式:
private static void mainForm_FormClosing(object sender, FormClosingEventArgs e)
{
UpdatingForm pbar = new UpdatingForm ();
pbar.Show();
}
in my updatingform: 在我的更新表格中:
public UpdatingForm()
{
InitializeComponent();
bgWorker.RunWorkerAsync();
}
private void bgWorker_DoWork(object sender, DoWorkEventArgs e)
{
....
}
private void bgWorker_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
{
this.Close();
// Application.Exit();
}
Setting e.Cancel
to true
is correct. 将e.Cancel
设置为true
是正确的。 However, once your UpdatingForm
closes, Application.Exit()
fires the mainForm_FormClosing()
event again, so you get one more UpdatingForm
etc. 但是,一旦您的UpdatingForm
关闭, Application.Exit()
会再次触发mainForm_FormClosing()
事件,因此您又获得了一个UpdatingForm
等。
private static bool isClosing = false;
private static void mainForm_FormClosing(object sender, FormClosingEventArgs e)
{
if (!isClosing)
{
isClosing = true;
e.Cancel = true;
UpdatingForm pbar = new UpdatingForm ();
pbar.Show();
}
}
Maybe this code works.test it 也许这段代码有效。测试它
private static void mainForm_FormClosing(object sender, FormClosingEventArgs e)
{
UpdatingForm pbar = new UpdatingForm ();
pbar.Show();
while (pbar.Created)
{
Application.DoEvents()
}
}
or 要么
private static void mainForm_FormClosing(object sender, FormClosingEventArgs e)
{
UpdatingForm pbar = new UpdatingForm ();
pbar.Show();
while (! pbar.IsDisposed)
{
Application.DoEvents()
}
}
Have you checked this article 你看过这篇文章吗
C# BackGroundWorker with ProgressBar Updates after process complete 具有ProgressBar的C#BackGroundWorker在过程完成后更新
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.