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

Louis Rhys picture Louis Rhys · Feb 20, 2013 · Viewed 16k times · Source

In .NET Process.GetProcessById throws an exception if the process with this ID is not running. How to safely call this method so that it won't throw an exception? I am thinking something like

if(Process.IsRunning(id)) return Process.GetProcessById(id);
else return null; //or do something else

But can't find any method to check the ID, other than probably getting all the running processes and check whether the id exist in the list.

Answer

Dmitry Dovgopoly picture Dmitry Dovgopoly · Feb 20, 2013
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.