Visual Basic 性能计数器不起作用

Visual Basic Performance Counter Doesn't Work

好的,所以我尝试在 Visual Studio 2010 中使用 PerformanceCounter 获取 CPU 用法,但我遇到的问题是当我添加 PerformanceCounter 并尝试添加 CategoryName 列表与 CounterNameInstanceName 一起为空。

我也尝试使用以下代码添加计数器,但它仍然不起作用:

Imports System.Diagnostics

Dim myCounter As System.Diagnostics.PerformanceCounter = New System.Diagnostics.PerformanceCounter()

myCounter.CategoryName = "Processor"
myCounter.CounterName = "% Processor Time"
myCounter.InstanceName = "_Total"

ProgressBar1.Value = myCounter.NextValue.ToString
cpuTxt.Text = "CPU Usage: " & ProgressBar1.Value.ToString & "%"

知道为什么会这样吗?我已经搜索了一段时间,但仍然无法正常工作。非常感谢任何帮助。

图片:http://s11.postimg.org/y0vnpiwcz/screen.jpg

这里可能有几个因素在起作用,PerformanceCounters 需要在使用前创建,此操作需要管理员访问计算机或充分升级。

您会注意到在 MSDN 提供的示例中,如果计数器当前不存在,则有条件地创建计数器。

https://msdn.microsoft.com/en-us/library/system.diagnostics.performancecounter%28v=vs.110%29.aspx

我假设您实际上是在轮询计数器?尝试这样的事情:

Option Strict On
Option Explicit On
Option Infer Off

Imports System.Diagnostics

Public Class Form1

    Private myCounter As System.Diagnostics.PerformanceCounter = New System.Diagnostics.PerformanceCounter()
    Private WithEvents poll As New Timer

    Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
        myCounter.CategoryName = "Processor"
        myCounter.CounterName = "% Processor Time"
        myCounter.InstanceName = "_Total"
        poll.Interval = 1000
        poll.Enabled = True
    End Sub

    Private Sub poll_Tick(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles poll.Tick
        Dim val As Single = myCounter.NextValue
        ProgressBar1.Value = CInt(val)
        cpuTxt.Text = "CPU Usage: " & val.ToString & "%"
    End Sub

End Class

正如 Hans PassantPlutonix 都在评论中指出的那样,您应该只创建计数器对象 一次。每次重新创建计数器只会导致读数为 0。