2013-12-12 31 views
0

我正在構建一個快速的進程cpu使用率檢測程序,我在這裏與PerformanceCounter有一些小問題。PerformanceCounter多個進程

如果我添加一個PerformanceCounter對象,並在GUI上的屬性分隔符正確的值我有這個工作。但是這個工作只適用於1個固定的過程。所以我想要做的是獲得價值的動態方法。 Look:

Private Function getCPUByProcessName(ByVal proc As String) as Single 
     Return New PerformanceCounter("Process", "% Processor Time", proc).NextValue() 
End Function 

此函數必須返回%,而不是。如果我嘗試通過在類上編碼來獲得固定進程%CPU使用率,那麼它不起作用。但是,如果我只是去圖形用戶界面,並從工具箱添加並編輯屬性,以促成它的工作懶惰。 :/

TL; DR:上述功能不起作用。總是返回0.0

更正後的代碼:

Public ProcDic As New Dictionary(Of Integer, PerformanceCounter) 

Private Function getCPUByProcess(ByRef proc As Process) As Single 
     If Not ProcDic.ContainsKey(proc.Id) Then 
      ProcDic.Add(proc.Id, New PerformanceCounter("Process", "% Processor Time",proc.ProcessName)) 
     End If 
     Return ProcDic.Item(proc.Id).NextValue() 
End Function 

回答

1

可不行,你必須使用完全相同的PerformanceCounter對象以獲得可靠的值NextValue()。現在你每次都創建一個新的,所以它總是從頭開始。 NextValue將始終爲0.它需要留下來收集歷史記錄。

只需使用Dictionary(Of Integer, PerformanceCounter)來跟蹤現有的計數器。使用Process.Id屬性作爲鍵。

+0

感謝它現在工作ehehe :) – int3