Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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.

like image 246
Louis Rhys Avatar asked Feb 20 '13 08:02

Louis Rhys


1 Answers

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.

like image 111
Dmitrii Dovgopolyi Avatar answered Oct 01 '22 13:10

Dmitrii Dovgopolyi