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

In .NET, an Process.GetProcessByIdexception is thrown if a process with this identifier is not running. How to safely call this method so that it does not throw an exception? I think something like

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

But it is not possible to find any method for checking the identifier, except, possibly, getting all running processes and checking for the identifier in the list.

+5
source share
3 answers
public Process GetProcByID(int id)
{
    Process[] processlist = Process.GetProcesses();
    return processlist.FirstOrDefault(pr => pr.Id == id);
}

I looked inside Process.GetProcessById.

ProcessManager, , . ProcessManager , , , , .

, Process.

+9

try-catch

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

}
return p;
+1

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

0
source

All Articles