通过使用以下代码我试图检索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
答案 0 :(得分:3)
是的,你做错了。每次调用方法时,都会创建一个 new 计数器。它的第一个报告值将始终为零,因为它没有前一个时间间隔的任何历史记录。相反,您只需创建一次计数器。最好在表单构造函数中完成:
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