Reputation: 1351
The software starts thread with some calculations and then shows another Form
as a waiting dialog with ShowDialog
. When the BackgroundWorker
thread finishes its work, the Form
is closed in the RunWorkerCompleted
event and another calculation is start with another Form
as a waiting dialog (with ShowDialog
again).
The problem is that the first waiting dialog is still visible until the second waiting dialog is closed. How to wait with showing the second dialog after the first dialog is really closed?
Simple code to reproduce:
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();
}
Upvotes: 2
Views: 1327
Reputation: 273179
Note that ShowDialog() is a blocking call. You still have not returned from the constructor when you show _msg2.
This is a quick fix:
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
}
Upvotes: 4