0

I'm working in a program that it needs to get the current CPU Usage How i can achieve that in vb.Net i tried like 4 codes but i still get 0% every time . here is one example of what i've used Link

Thanks In Advance , Anes08

Anes08
  • 103
  • 3
  • 14

3 Answers3

2

you can use LblCpuUsage.text = CombinedAllCpuUsageOfEachThread.NextValue() .There is a helper library to get that information:

The Performance Data Helper (see Using the PDH Functions to Consume Counter Data (Windows)[^])

.

Microsoft examples are in C but there are also corresponding VB (not .Net) functions:

Performance Counters Functions for Visual Basic (Windows)[^]

Datacrawler
  • 2,780
  • 8
  • 46
  • 100
2

Though it is not allowed to answer such questions,but still , here's something that might help you get started :

   Dim cpu as New System.Diagnostics.PerformanceCounter 
   cpu.CategoryName = "Processor"
   cpu.CounterName = "% Processor Time"
   cpu.InstanceName = "_Total"
   MessageBox(cpu.NextValue.ToString + "%")

If it doesn't work , here's a better version:

  Dim cpu as PerformanceCounter  '''Declare in class level

 'On form load(actually you need to initialize it first)

  cpu = new PerformanceCounter("Processor", "% Processor Time", "_Total")

  '''Finally,get the value :

  MsgBox(cpu.NextValue & "%") '''Use .ToString if required
Software Dev
  • 5,368
  • 5
  • 22
  • 45
0

For me I wanted an average. There were a couple problems getting CPU utilization that seemed like there should be an easy package to solve but I didn't see one.

The first is of course that a value of 0 on the first request is useless. Since you already know that the first response is 0, why doesn't the function just take that into account and return the true .NextValue()?

The second problem is that an instantaneous reading may be wildly inaccurate when trying to make decisions on what resources your app may have available to it since it could be spiking, or between spikes.

My solution was to do a for loop that cycles through and gives you an average for the past few seconds. you can adjust the counter to make it shorter or longer (as long as it is more than 2).

public static float ProcessorUtilization;

public static float GetAverageCPU()
{
    PerformanceCounter cpuCounter = new PerformanceCounter("Process", "% Processor Time", Process.GetCurrentProcess().ProcessName);
    for (int i = 0; i < 11; ++i)
    {
        ProcessorUtilization += (cpuCounter.NextValue() / Environment.ProcessorCount);
    }
    // Remember the first value is 0, so we don't want to average that in.
    Console.Writeline(ProcessorUtilization / 10); 
    return ProcessorUtilization / 10;
}
Alan
  • 2,046
  • 2
  • 20
  • 43