What I'm trying to achieve is to show FirstForm during long operation. When this operation ends I'd like to close FirstForm and show SecondForm. Below is sample code: for my suprise Close is not working (both forms are visible).
using System;
using System.Windows.Forms;
using System.Threading.Tasks;
namespace WindowsFormsApplication1
{
static class Program
{
[STAThread]
static void Main()
{
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
Application.Run(new FormMain());
}
}
class FormMain : Form
{
public FormMain()
{
var button = new Button() { Text = "test" };
button.Click += (o, e) =>
{
var first = new FormFirst();
Task.Factory.StartNew(() =>
{
////some long operation...
}).ContinueWith(t => {
first.Close();
var second = new FormSecond();
second.ShowDialog();
}, TaskScheduler.FromCurrentSynchronizationContext());
first.ShowDialog();
};
Controls.Add(button);
}
}
class FormFirst : Form
{
public FormFirst() { Text = "First"; }
}
class FormSecond : Form
{
public FormSecond() { Text = "Second"; }
}
}
I solved this using Form.Invoke but is this a proper way?:
var first = new FormFirst();
Task.Factory.StartNew(() =>
{
////some long operation...
var created = new AutoResetEvent(first.IsHandleCreated);
first.HandleCreated += (o1,e1) => created.Set();
created.WaitOne();
first.Invoke(new Action(() => first.Close()));
}).ContinueWith(t =>
{
first.Close();
var second = new FormSecond();
...