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
Process.GetProcessById
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.
public Process GetProcByID(int id) { Process[] processlist = Process.GetProcesses(); return processlist.FirstOrDefault(pr => pr.Id == id); }
I looked inside Process.GetProcessById.
ProcessManager, , . ProcessManager , , , , .
, Process.
Process
try-catch
Process p = null; try{ p = Process.GetProcessById(id); } catch(Exception){ } return p;
Yes, using try + catch is likely to do the trick. If the process is not running, nothing will happen, instead of throwing an exception.