Visual Basic性能计数器不起作用

时间:2015-05-16 16:58:58

标签: vb.net visual-studio-2010 performancecounter

好的,我试图在Visual Studio 2010中使用PerformanceCounter来获取CPU使用率,但我遇到的问题是当我添加PerformanceCounter并尝试添加时CategoryName列表为CounterName以及InstanceNameImports 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 & "%"

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

forever start peerjs --port 9000 --key peerjs

知道为什么会这样吗?我现在已经找了一段时间,仍然无法让它发挥作用。非常感谢任何帮助。

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

2 个答案:

答案 0 :(得分: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 Passant Plutonix 都在评论中指出,您应该只创建一个计数器对象一次。每次重新创建计数器只会导致读数为0.

答案 1 :(得分:0)

此处可能存在一些因素,PerformanceCounters需要在使用之前创建,此操作需要管理员访问计算机或进行足够的升级。

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

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