Reputation: 185
Can anybody tell me why this doesn't work. My guess is its something to do with instantiation or the global values.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Diagnostics;
using System.Threading;
using System.Speech.Synthesis;
namespace UtilApp
{
class Perf
{
#region Performance Counters
// CPU utilization
PerformanceCounter CPU_Perf = new PerformanceCounter("Processor Information", "% Processor Time", "_Total");
// Memory left
PerformanceCounter MEM_Perf = new PerformanceCounter("Memory", "Available MBytes");
// System Up time
PerformanceCounter SYS_Perf = new PerformanceCounter("System", "System Up Time");
#endregion
public int getUsedCPU()
{
Console.WriteLine("Requested CPU Usage...");
int v = (int) CPU_Perf.NextValue();
Console.WriteLine("Value: {0}", v);
return v;
}
public int getFreeMEM()
{
return (int) MEM_Perf.NextValue();
}
public int getUpTime()
{
return (int) SYS_Perf.NextValue();
}
}
}
Basically, getUsedCPU() always returns 0, when I know that is not true. I copied this over from a console application I built using a tutorial online.
I'm accessing it from a form to show CPU usage like so...
Perf p = new Perf;
label1.text = p.getUsedCPU().toString();
NOTE: the console.writeline are for debugging, but still get 0 without them.
Upvotes: 0
Views: 274
Reputation: 193
Add a class constructor, then create the instance of objects:
PerformanceCounter CPU_Perf;
PerformanceCounter MEM_Perf;
PerformanceCounter SYS_Perf;
public Perf()
{
PerformanceCounter CPU_Perf = new PerformanceCounter("Processor Information", "% Processor Time", "_Total");
PerformanceCounter MEM_Perf = new PerformanceCounter("Memory", "Available MBytes");
PerformanceCounter SYS_Perf = new PerformanceCounter("System", "System Up Time");
}
Upvotes: 0
Reputation: 53958
From the MSDN
If the calculated value of a counter depends on two counter reads, the first read operation returns 0.0.
So, if you call once more the method, then you will get that you are looking for.
Furthermore, from here:
To obtain performance data for counters that required an initial or previous value for performing the necessary calculation, call the NextValue method twice and use the information returned as your application requires.
Why this happens?
This happens, as Jon mentioned in his comment, because the OP is creating a new instance of Perf
each time.
Upvotes: 4