ASP.NET Performance Counter always return 0

The solution is to sleep 1 second between the calls to NextValue.

In VB:

Dim cpu As New PerformanceCounter("Processor", "% Processor Time", "_Total", "servername")

cpu.NextValue()

System.Threading.Thread.Sleep(1000)

MyValue = cpu.NextValue()

It's hard to know if it's still returning the correct number, but it's very close (within 1 point) to what perfmon shows. I tried it with 2 seconds also and it appears to be a bit closer to what perfmon shows.

From http://blogs.msdn.com/b/dotnetinterop/archive/2007/02/02/system-diagnostics-performancecounter-and-processor-time-on-multi-core-or-multi-cpu.aspx:

Keep in mind that you need to delay "about 1 second" between calls to NextValue(), as per the documentation!

...and links to https://msdn.microsoft.com/en-us/library/system.diagnostics.performancecounter.nextvalue.aspx, which states:

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.

Tags:

C#

Vb.Net

Asp.Net