PerformanceCounter多个进程

时间:2013-12-12 23:17:38

标签: vb.net process wmi

我正在构建一个快速进程cpu使用检测程序,我在这里遇到一个与PerformanceCounter有点问题。

如果我添加一个PerformanceCounter对象并在GUI上的属性分隔符上放置正确的值,我就可以了。但这项工作只适用于1个固定过程。所以我想要做的是获得价值的动态方式。 看:

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

此函数必须返回%,而不是。如果我尝试通过在类上编码获得固定进程%cpu使用率它不起作用。但是,如果我只是去GUI并从工具箱添加并编辑属性以促成它的工作懒惰。 :/

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 个答案:

答案 0 :(得分:1)

这不起作用,必须使用完全相同的PerformanceCounter对象来获取NextValue()的可靠值。现在你每次都创建一个新的,所以它总是从头开始。 NextValue将永远为0.它需要留下来收集历史。

只需使用Dictionary(Of Integer, PerformanceCounter)即可跟踪现有计数器。使用Process.Id属性作为键。

相关问题