我正在构建一个快速进程cpu使用检测程序,我在这里遇到了PerformanceCounter的一个小问题。
如果我添加了一个PerformanceCounter对象,并在GUI上的属性分隔符上放置了正确的值,我就可以做到这一点。但是这个工作只适用于一个固定的过程。所以我想做的是一种动态的方法来获得这些值。看:
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发布于 2013-12-12 23:22:56
这是行不通的,您必须使用完全相同的PerformanceCounter对象来获得NextValue()的可靠值。现在,您每次创建一个新的,所以它总是从零开始。NextValue永远是0。它需要留下来收集历史。
只需使用Dictionary(Of Integer, PerformanceCounter)跟踪现有计数器。使用Process.Id属性作为键。
https://stackoverflow.com/questions/20556240
复制相似问题