The code runs fine, but I am getting nothing as an output...
No, the code doesn't run fine:
- You're never being told about the error because of your exception handling.
- If the code runs fine then it would produce output.
Your code explicitly ignores any error that results in an InvalidOperationException
. Exceptions are there for a reason, usually to tell you that there is something seriously wrong. The only time you should use should ignore them is when you really, really don't care that an exception has occurred.
In your code you set CategoryName
to indicate which group of counters you're looking at, but never set the CounterName
property to specify which counter to use. And in the case of the Processor
group, since there are potentially multiple processors.
Next problem, the first result you get from cpuCounter.Nextvalue()
is groing to be 0.0
. Always. The NextValue
method gets a sample from the counter and compares it to the last sample to calculate an actual value. Necessarily this requires two calls to NextValue
with a delay between in order to get a valid result. That delay should be at least a second.
Here's some code that fixes a few of the problems:
public class CPUTime : IDisposable
{
private PerformanceCounter counter;
private DateTime lastcheck;
private float lastvalue;
public float Value
{
get
{
if ((DateTime.Now - lastcheck).TotalMilliseconds > 950)
{
lastvalue = counter.NextValue();
lastcheck = DateTime.Now;
}
return lastvalue;
}
}
public CPUTime()
{
counter = new PerformanceCounter("Processor", "% Processor Time", "_Total", true);
counter.NextValue();
lastcheck = DateTime.Now;
}
~CPUTime()
{
Dispose();
}
public void Dispose()
{
if (counter != null)
{
counter.Dispose();
counter = null;
}
}
public override string ToString()
{
return string.Format("{0:0.00}%", Value);
}
}
If that's not fast enough for you - it only updates once per second, after all - then you'll need to use the GetSystemTimes
API call and do your own calculations. It still needs two samples, but you can call it much more frequently and get reasonable results.