I'm having trouble getting my GUI to appear and not freeze while running (and waiting for) an outside process. In this case, drivers.exe is a very simply program where the user simply clicks "OK". So whenever I click OK, it exits. I am trying to simply make my status strip count numbers up (really fast) as drivers.exe is executing. But in practice, my GUI never appears at all until drivers.exe exits.
private void run_drivers()
{
Console.WriteLine("Start Driver");
int driver_timeout_in_minutes = 20;
System.Diagnostics.Process driverproc = System.Diagnostics.Process.Start(Application.StartupPath + "\\" + "drivers.exe");
driverproc.WaitForExit(driver_timeout_in_minutes * 1000 * 60); //uses milliseconds, we must convert
}
private void Form1_Load(object sender, EventArgs e)
{
ThreadStart worker = new ThreadStart(run_drivers);
Console.WriteLine("Main - Creating worker thread");
toolStripStatusLabel1.Text = "hi";
Thread t = new Thread(worker);
t.IsBackground = true;
t.Start();
Console.WriteLine("Main - Have requested the start of worker thread");
int i = 0;
while (t.IsAlive)
{
i++;
toolStripStatusLabel1.Text = i.ToString();
}
Console.WriteLine("Dead");
}
You should look into a BackgroundWorker, as it does all the threading work for you
The reason that your form does not show until drivers.exe has run is because you are running drivers.exe from within Form.Load
. Form.Load
occurs before the form is shown. Try running drivers.exe in Form.Shown
instead.
Also, while(t.IsAlive)
will technically block your UI thread. If that is not what you want, it should be moved off the main thread. You will also probably want to call toolStripStatusLabel1.Refresh()
to force the label to refresh after you set its text.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With