How to check if process is still running before calling Process.GetProcessById?

Yeah, using try + catch will probably do the trick. If the process is not running, nothing will happen instead of throwing an exception.


public Process GetProcByID(int id)
{
    Process[] processlist = Process.GetProcesses();
    return processlist.FirstOrDefault(pr => pr.Id == id);
}

I looked inside Process.GetProcessById method.

It uses internal static class ProcessManager to ensure, that process runs. ProcessManager gets all the processes currently running in system and checks there ids, so I think it is the best way to do it.

So you should consider the overhead of exception or the overhead of Process array.


Just use try-catch block

Process p = null;
try{
  p = Process.GetProcessById(id);
}
catch(Exception){

}
return p;