1

By using Following Code i am trying to retrieve the CPU Usages, but its always return 0, i am also using timer in code so that the following function calling every 5 sec,

But the strange thing is that ,if i use the PerformanceCounter control then code its work perfectly ,but if i use PerformanceCounter class the its not working.

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
4

1 回答 1

3

Yes, you are doing it wrong. You create a new counter every time you call the method. Its first reported value will always be zero since it doesn't have any history yet of the previous time interval. Instead, you need to create the counter just once. Best done in the form constructor:

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
于 2013-09-25T13:51:00.047 回答