Search code examples
c#wpfmultithreadingsleep

Should I use Thread.Sleep() to check if a process is still running?


As title says, I'm currently making a WPF application and I need to detect if an application is running and do something when it's closed. The way I'd thought of doing so is by running a separate Thread and checking every two seconds if the process is still running, something like this:

while(Process.GetProcessesByName(processName).Length != 0) {
    Thread.Sleep(2000);
}

//Do something

Would this be a good solution, is there any other way of doing this?

Thanks


Solution

  • Since you are already dealing with Processes, I would suggest just using it directly to determine if it has exited. You can use the Exited event handler for your code. So, for instance:

    foreach (var process in Process.GetProcessesByName(processName))
    {
      process.Exited += new EventHandler(DoSomething);
    }
    
    …
    
    public void DoSomething(object sender, System.EventArgs e)
    {
      // do something
    }
    

    This will call DoSomething when the process with that name ends.