Search code examples
c#.netprocesspid

How to determine if a process ID exists


I'm using C# .NET 2.0. I need to determine if a PID exists. I came up with the following code:

private bool ProcessExists(int iProcessID)
{
    foreach (Process p in Process.GetProcesses())
    {
        if (p.Id == iProcessID)
        {
            return true;
        }
    }
    return false;
}

Is there a better way to do this other than iterating all the processes?


Solution

  • Quick Note: You can't ever determine if a process, other than your own, is running. You can only tell that it was running at some point in the recent past. A process can simply cease to exist at any given moment including the exact moment you check to see if it has a matching ID.

    That being said, this type of determination may or may not be good enough for your program. It really depends on what you are trying to do.

    Here is an abbreviated version of the code you wrote.

    private bool ProcessExists(int id) {
      return Process.GetProcesses().Any(x => x.Id == id);
    }