如何等到对话框真正关闭
How to wait until the dialog is really closed
软件启动线程进行一些计算,然后显示另一个 Form
作为与 ShowDialog
的等待对话框。当 BackgroundWorker
线程完成其工作时,Form
在 RunWorkerCompleted
事件中关闭,另一个计算开始,另一个 Form
作为等待对话框(ShowDialog
)。
问题是第一个等待对话框在第二个等待对话框关闭之前仍然可见。如何在第一个对话框真正关闭后等待显示第二个对话框?
简单的重现代码:
private BackgroundWorker _bgw = new BackgroundWorker();
private Form2 _msg = new Form2();
private Form3 _msg2 = new Form3();
public Form1()
{
_bgw.DoWork += BgwDoWork;
_bgw.RunWorkerCompleted += BgwRunWorkerCompleted;
_bgw.RunWorkerAsync();
_msg.ShowDialog();
}
private void BgwDoWork(object sender, DoWorkEventArgs e)
{
System.Threading.Thread.Sleep(5000);
}
private void BgwRunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
{
_msg.Close();
_msg2.ShowDialog();
}
请注意 ShowDialog() 是一个阻塞调用。当您显示 _msg2 时,您仍然没有从构造函数返回。
这是一个快速修复:
public Form1()
{
_bgw.DoWork += BgwDoWork;
_bgw.RunWorkerCompleted += BgwRunWorkerCompleted;
_bgw.RunWorkerAsync();
_msg.ShowDialog();
_msg2.ShowDialog(); // here
}
private void BgwRunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
{
_msg.Close();
//_msg2.ShowDialog(); // not here
}
软件启动线程进行一些计算,然后显示另一个 Form
作为与 ShowDialog
的等待对话框。当 BackgroundWorker
线程完成其工作时,Form
在 RunWorkerCompleted
事件中关闭,另一个计算开始,另一个 Form
作为等待对话框(ShowDialog
)。
问题是第一个等待对话框在第二个等待对话框关闭之前仍然可见。如何在第一个对话框真正关闭后等待显示第二个对话框?
简单的重现代码:
private BackgroundWorker _bgw = new BackgroundWorker();
private Form2 _msg = new Form2();
private Form3 _msg2 = new Form3();
public Form1()
{
_bgw.DoWork += BgwDoWork;
_bgw.RunWorkerCompleted += BgwRunWorkerCompleted;
_bgw.RunWorkerAsync();
_msg.ShowDialog();
}
private void BgwDoWork(object sender, DoWorkEventArgs e)
{
System.Threading.Thread.Sleep(5000);
}
private void BgwRunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
{
_msg.Close();
_msg2.ShowDialog();
}
请注意 ShowDialog() 是一个阻塞调用。当您显示 _msg2 时,您仍然没有从构造函数返回。
这是一个快速修复:
public Form1()
{
_bgw.DoWork += BgwDoWork;
_bgw.RunWorkerCompleted += BgwRunWorkerCompleted;
_bgw.RunWorkerAsync();
_msg.ShowDialog();
_msg2.ShowDialog(); // here
}
private void BgwRunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
{
_msg.Close();
//_msg2.ShowDialog(); // not here
}