有人能告诉我为什么这不管用吗。我猜想这与实例化或全局值有关。
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
来自MSDN
如果计数器的计算值依赖于两个计数器读取,则第一个读取操作返回0.0。
因此,如果您再次调用该方法,那么您将得到您正在寻找的方法。
此外,来自这里
若要获取用于执行必要计算所需的初始或先前值的计数器的性能数据,请两次调用NextValue方法并使用应用程序要求返回的信息。 为什么会发生这种事?
正如Jon在他的评论中提到的那样,这是因为OP每次都在创建一个新的Perf实例。
发布于 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
复制相似问题