Question

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?

Was it helpful?

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);
}

OTHER TIPS

The risky thing here is: Where did you get that Process ID from? If it's just a number you saved sometime earlier, the original process could have died and a new process could be running with the same ID.

What are you trying to accomplish? There may be a better way of achieving your actual goal.

System.Diagnostics.Process.GetProcessById(iProcessID) would throw ArgumentException if the process doesn't exist. Although that is not the best way to check if the process exists, but hopefully this is what you're looking for.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top