John Ryann
John Ryann

Reputation: 2393

GUI Winform and ending /killing process

I have a c# GUI app and it's running a bunch of command line process one after another. How do I end/kill the app while the command line process is running? I have an Exit button (button 3) but it's not working if the process called is still running.

private void Run_Process(string process_to_run, string p_arg)
    {
        Process myProcess = new Process();
        richTextBox1.AppendText("\nRunning " + process_to_run);

        try
        {
            myProcess.StartInfo.UseShellExecute = false;
            myProcess.StartInfo.FileName = process_to_run;
            myProcess.StartInfo.Arguments = p_arg;
            myProcess.StartInfo.CreateNoWindow = true;
            myProcess.Start();
            myProcess.WaitForExit();
            richTextBox1.AppendText("...Success");
            time_date = get_time();
            log_file.Write(time_date);
            log_file.WriteLine(process_to_run + "...Success");

        }

        catch (Exception ep)
        {
            richTextBox1.AppendText("\n" + ep.Message);
            time_date = get_time();
            log_file.Write(time_date);
            log_file.WriteLine(process_to_run + "...Failed. ERROR: " + ep.Message);
        }
    }     

  private void button3_Click(object sender, EventArgs e)
    {
        db.connection.Close();
        Application.Exit();
    }

Upvotes: 2

Views: 1198

Answers (4)

Roshan Patil
Roshan Patil

Reputation: 1

Environment.Exit(1); really works.

Upvotes: 0

Steven P
Steven P

Reputation: 1996

If you need to exit, and exit now, try Environment.Exit.

Environment.Exit Method

Terminates this process and gives the underlying operating system the specified exit code.

Upvotes: 0

David Merriman
David Merriman

Reputation: 6086

You have a call to myProcess.WaitForExit(); in Run_Process. If Run_Process gets called from the main thread, you're going to block that thread until the command line tool finishes. That means button3_Click() can't fire until after myProcess has completed.

Upvotes: 0

Reed Copsey
Reed Copsey

Reputation: 564403

Right now, you're waiting for the process to exit:

myProcess.WaitForExit();

If this is happening in the UI thread, then you won't be able to exit (cleanly) until the method finishes, which means you have to wait for the process to finish.

If, instead, you don't wait on the process, you'll be able to exit immediately.

You should be able to rework your logic to not block by setting Process.EnableRaisingEvents and then subscribing to the Exited event on the process. You can add your text to your RichTextBox in this event, instead of blocking the main thread.

Upvotes: 1

Related Questions