2012-03-05 181 views
1

爲什麼下面的代碼引發錯誤Instance 'taskmgr' does not exist in the specified Category.時,我沒有通過PARAMS在構造函數爲什麼在PerformanceCounter對象上調用NextValue()會拋出錯誤?

var cpuCounter = new PerformanceCounter(); 
cpuCounter.CategoryName = "Processor"; 
cpuCounter.CounterName = "% Processor Time";    
cpuCounter.InstanceName = "taskmgr"; 
cpuCounter.NextValue(); 

但是,當我做同樣通過傳遞PARAMS在構造函數不會引發錯誤。

var cpuCounter = new PerformanceCounter(
    "Processor", 
    "% Processor Time", 
    "taskmgr"); 
cpuCounter.NextValue(); 

更新: 我試着在每一個進程的名稱,不僅是「taskmgr」,結果是一樣的!

什麼問題?

+0

實際上它給了同樣的錯誤了我在這兩種情況下 – ionden 2012-03-05 16:10:59

+0

你確定taskmgr實際上運行時,你執行這兩個代碼塊? – ken2k 2012-03-05 16:13:24

+0

是的。我已經仔細檢查過了。它發生在我把每個進程名稱 – theateist 2012-03-05 16:17:15

回答

1

有可用於Processor類別沒有taskmgr實例,因爲Processor是關於你的CPU ...

你可能是指Process,預期其工作原理:

var cpuCounter = new PerformanceCounter(); 
cpuCounter.CategoryName = "Process"; 
cpuCounter.CounterName = "% Processor Time";    
cpuCounter.InstanceName = "taskmgr"; 
cpuCounter.NextValue(); 
+0

你是對的!這解決了這個問題。但是,對於'CategoryName =「Processor」'爲什麼它只在我通過參數傳遞時才起作用? – theateist 2012-03-05 16:43:43

+0

@theateist你能提供一個可重複的例子嗎?我剛剛以0爲例來測試處理器(即您的機器的第一個核心),它適用於我的兩種情況。 – ken2k 2012-03-05 16:46:49

0

您確定要爲CategoryName/InstanceName提供正確的值嗎?從documentation for InstanceName看來,實例名稱應該與通過性能監視器MMC管理單元可用的值匹配,它至少在提供"Processor"時,僅爲我的計算機上的處理器提供_Total和整數索引。

如果您爲CategoryName提供"Process"它允許查看過程。

相關問題