ultramoo ultramoo - 2 months ago 47
C# Question

Getting process instance name from a process id / object (Faster way)

Currently, the solution to get a Instance Name from a Process ID is from the code below.
Problem is, this takes a lot of time and CPU resources!

That is to say when you have a system that's running at least 100 processes, it takes a considerable amount of time to cycle through the loops to find it. (like 1 to 2 seconds) And when I am looking to find up to 30 of those processes, it takes up to 30 seconds to find them all...

Can't you simply get a instance name from a process object?

private static string GetProcessInstanceName(int pid)
{
PerformanceCounterCategory cat = new PerformanceCounterCategory("Process");

string[] instances = cat.GetInstanceNames();
foreach (string instance in instances)
{

using (PerformanceCounter cnt = new PerformanceCounter("Process",
"ID Process", instance, true))
{
int val = (int) cnt.RawValue;
if (val == pid)
{
return instance;
}
}
}
throw new Exception("Could not find performance counter " +
"instance name for current process. This is truly strange ...");
}

Answer

Why not use the System.Diagnostics.Process.GetProcessById function?

private static string GetProcessInstanceName(int pid)
{ 
    string name = String.Empty;
    Process proc = System.Diagnostics.Process.GetProcessById(pid);
    if(proc != null)
    {
        name = proc.ProcessName;
    }
    return name;
}
Comments