34

In C#, I can start a process with

process.start(program.exe);

How do I tell if the program is still running, or if it closed?

5 Answers 5

75

MSDN System.Diagnostics.Process

If you want to know right now, you can check the HasExited property.

var isRunning = !process.HasExited;

If it's a quick process, just wait for it.

process.WaitForExit();

If you're starting one up in the background, subscribe to the Exited event after setting EnableRaisingEvents to true.

process.EnableRaisingEvents = true;
process.Exited += (sender, e) => {  /* do whatever */ };
1
  • 1
    This approch doesnt work for ASP.NET, not real asynch run. My web application is blocked while process is running. Any Idea?
    – Siyon DP
    Commented May 10, 2023 at 8:47
19
Process p = new Process();
p.Exited += new EventHandler(p_Exited);
p.StartInfo.FileName = @"path to file";
p.EnableRaisingEvents = true;
p.Start();

void p_Exited(object sender, EventArgs e)
{
    MessageBox.Show("Process exited");
}
3

Be sure you save the Process object if you use the static Process.Start() call (or create an instance with new), and then either check the HasExited property, or subscribe to the Exited event, depending on your needs.

2
  • You can use the Process.Start(string) method since it returns an instance of Process. You can use that instance's Exited event.
    – Mike Mayer
    Commented Sep 5, 2012 at 2:48
  • @MikeMayer Good point; I always forget it works like that. Will edit. Commented Sep 5, 2012 at 2:49
1

Assign an event handler to the Exited event.

There is sample code in that MSDN link - I won't repeat it here.

1

Take a look at the MSDN documentation for the Process class.

In particular there is an event (Exited) you can listen to.

Not the answer you're looking for? Browse other questions tagged or ask your own question.