views:

15

answers:

1

When querying instances for the the "Process" performance counter category there might be multiple instances of of a process with the same name.

For example this code:

var cat = new PerformanceCounterCategory("Process");

var names = cat.GetInstanceNames();

foreach (var name in names)
    Console.WriteLine(name);

Might print these results: ... iexplore iexplore#1 iexplore#2 iexplore#3 ...

How do I know which process each of these counter instances corresponds to?

+2  A: 

There is a PerformanceCounter named "ID Process" in the "Process" category that will return the pid of the process that the performance counter instance corresponds to.

var cat = new PerformanceCounterCategory("Process");

var names = cat.GetInstanceNames();

foreach (var name in names.OrderBy(n => n))
{
    var pidCounter = new PerformanceCounter("Process", "ID Process", name, true);
    var sample = pidCounter.NextSample();
    Console.WriteLine(name + ": " + sample.RawValue);
}

This will print:

...

iexplore: 548

iexplore#1: 1268

iexplore#2: 4336

...

Mark