Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Running another process without GUI freezing

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");
        }
like image 802
Adam Avatar asked Mar 09 '10 02:03

Adam


2 Answers

You should look into a BackgroundWorker, as it does all the threading work for you

like image 156
Dan McClain Avatar answered Oct 31 '22 17:10

Dan McClain


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.

like image 44
Zach Johnson Avatar answered Oct 31 '22 18:10

Zach Johnson