2010-09-09 58 views
0

查詢「進程」性能計數器類別的實例時,可能會有多個具有相同名稱的進程的實例。使用Process PerformanceCounters我如何知道實例與哪個進程關聯?

例如下面的代碼:

var cat = new PerformanceCounterCategory("Process"); 

var names = cat.GetInstanceNames(); 

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

可能會打印這些結果: ... IEXPLORE IEXPLORE#1 IEXPLORE#2 IEXPLORE#3 ...

我如何知道每個這些計數器實例對應哪個進程?

回答

2

「Process」類別中有一個名爲「ID Process」的PerformanceCounter,它將返回性能計數器實例對應的進程的pid。

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

這將打印:

...

IEXPLORE:548

IEXPLORE#1:1268

IEXPLORE#2:4336

。 ..

相關問題