0

I have an application which keeps track of Windows process IDs and need to know whether a certain process ID is still running. Process xxxxx, is it running, true or false? I have a roundabout way of doing this in C# which I'm not happy with, namely

static long[] Processes() {
    long[] processes = new long[100000];
    ManagementClass m = new ManagementClass("Win32_Process");
    foreach (ManagementObject mobj in m.GetInstances()) {
       long t = (UInt32)mobj["ProcessId"];
       processes[t] = t;
    }
    return processes;
}

The idea here is that since there are only 100000 possible process ids, the function returns an array of 100000 longs. If process id xxxxx is running, then processids[xxxxx] is not zero. I refresh this list every minute or so. Yes, I know that there is always the risk that process id xxxxx may have been freshly started and it would count as a false positive.

Certainly there is a better (and faster) way?

Bill Early
  • 45
  • 4
  • Maybe take a look at `System.Diagnostics.Process.GetProcessById` and related classes. – 500 - Internal Server Error May 06 '21 at 22:27
  • Can you refer to https://stackoverflow.com/questions/178147/how-can-i-verify-if-a-windows-service-is-running – zia khan May 06 '21 at 23:03
  • Why not just query using linq real time? `if (Process.GetProcesses().Any(p => p.Id == pid))` – Kevin May 06 '21 at 23:13
  • I've got a lot of questions about this; first of them: Why? What is the rationale, what are you trying to achieve? But second, why would you create an array of 100K longs "try to match" to "any" existing process (a list which you already have -since you're iterating the instance list)? And many (MANY) more questions – riffnl May 06 '21 at 23:22

0 Answers0