1

I would like to find out the current CPU usage using the codes below(c# in asp.net framework). However it gives me "0% of CPU usage" when I try to run the program. When I check my task manager, I found out that the actual total CPU usage is more than 5%. Does anyone know what is wrong with the code below?

public partial class cpuUsage : System.Web.UI.Page { PerformanceCounter cpu; protected void Page_Load(object sender, EventArgs e) { cpu = new PerformanceCounter(); cpu.CategoryName = "Processor"; cpu.CounterName = "% Processor Time"; cpu.InstanceName = "_Total"; lblCPUUsage.Text = getCurrentCpuUsage(); } public string getCurrentCpuUsage() { return cpu.NextValue() + "%"; } } 
2
  • Since a lot of code is missing, I'll have to make a guess here: Are you re-initializing the PerformanceCounter every time you are trying to get a valu? It might be 0 because you only ever use it once. Commented Sep 16, 2016 at 6:56
  • @ManfredRadlwimmer, sorry, I have edited the codes to make it clearer Commented Sep 16, 2016 at 7:00

1 Answer 1

2

The first value returned by a PerformanceCounter will always be 0. You'll need a Timer or Thread that keeps monitoring the value in the background. This code for example will output the correct value every second (don't use this actual code, it's quick and dirty):

new Thread(() => { var cpu = new PerformanceCounter { CategoryName = "Processor", CounterName = "% Processor Time", InstanceName = "_Total" } while (true) { Debug.WriteLine("{0:0.0}%", cpu.NextValue()); Thread.Sleep(1000); } }).Start(); 

Make sure to read the remarks of the PerformanceCounter.NextValue method:

If the calculated value of a counter depends on two counter reads, the first read operation returns 0.0. Resetting the performance counter properties to specify a different counter is equivalent to creating a new performance counter, and the first read operation using the new properties returns 0.0. The recommended delay time between calls to the NextValue method is one second, to allow the counter to perform the next incremental read.

Sign up to request clarification or add additional context in comments.

2 Comments

is there a way to find the current CPU usage by a simple method call in C# ?
@Ammar This is as easy as it gets.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.