好的,我想在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

===============>>#1 票数:1 已采纳

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

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在评论中都指出的那样,您只应创建一次 counter对象。 每次重新创建计数器只会导致读数为0。

===============>>#2 票数:0

这里可能有两个因素在起作用,PerformanceCounters需要在使用前创建,此操作需要管理员访问计算机或进行足够的升级。

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

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

  ask by Brian Moreno translate from so

未解决问题?本站智能推荐: