有人能告诉我为什么这不管用吗。我猜想这与实例化或全局值有关。
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();
}
}
}基本上,当我知道不正确时,getUsedCPU()总是返回0。我从一个使用在线教程构建的控制台应用程序中复制了这些内容。
我从表单中访问它来显示CPU的使用情况.
Perf p = new Perf;
label1.text = p.getUsedCPU().toString();注意: console.writeline是用于调试的,但在没有它们的情况下仍然获得0。
发布于 2014-11-21 19:35:17
发布于 2014-11-21 19:43:38
添加类构造函数,然后创建对象的实例:
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");
}https://stackoverflow.com/questions/27068874
复制相似问题