性能计数器在vb.net中始终为零

约翰

通过使用“以下代码”,我试图检索CPU使用率,但是它始终返回0,因此我也在代码中使用了计时器,因此以下函数每5秒调用一次,

但是奇怪的是,如果我使用PerformanceCounter控件,则可以完美地编码它的工作,但是如果我使用PerformanceCounter类,则它不能工作。

Private Function GetAllCpuUsages()
    Dim cpucounter As New PerformanceCounter
    cpucounter.CategoryName = "Processor"
    cpucounter.CounterName = "% Processor Time"
    cpucounter.InstanceLifetime = PerformanceCounterInstanceLifetime.Global
    cpucounter.InstanceName = "_Total"
    cpucounter.MachineName = "."
    cpucounter.ReadOnly = True
    TextBox1.Text = Convert.ToInt32(cpucounter.NextValue).ToString()
    
End Function
汉斯·帕桑特

是的,您做错了。每次调用该方法时,都会创建一个新的计数器。它的第一个报告值将始终为零,因为它没有上一个时间间隔的任何历史记录。相反,您只需要创建一次计数器。最好在表单构造函数中完成:

Dim cpucounter As New PerformanceCounter

Public Sub New()
    InitializeComponent()
    cpucounter.CategoryName = "Processor"
    cpucounter.CounterName = "% Processor Time"
    cpucounter.InstanceName = "_Total"
    Timer1.Interval = 1000
    Timer1.Enabled = True
End Sub

Private Sub Timer1_Tick(sender As Object, e As EventArgs) Handles Timer1.Tick
    Label1.Text = Convert.ToInt32(cpucounter.NextValue).ToString()
End Sub

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章