从网上搜到的方法,以下代码可以得到CPU的使用率
const string categoryName = "Processor";
const string counterName = "% Processor Time";
const string instanceName = "_Total";
static PerformanceCounter cpuPerformance = new PerformanceCounter(categoryName, counterName, instanceName);
static float GetCPUUsage()
{
return cpuPerformance.NextValue();
}
然后现在的场景是这样的,我做了一个windows服务。在这个里面读取机器的CPU使用率,内存使用率等相关信息。由于需要不停的读取,所以这两个工作必须得放在另外的线程里面做。
我的项目用的.net 4.5
所以我一开始用了
Task.Run(()=>{
while(!stop)
{
GetCPUUsage();
}
});
调试时发现一到GetCPUUsage()就直接退出了,怎么Try catch都抓不到异常。我想可能读取CPU使用率不能放在Task.Run()里面。
然后改写了GetCPUUsage变为
static voidGetCPUUsage()
{
while(!stop)
{
float cpuUse= cpuPerformance.NextValue();
Console.WriteLine("CPU使用率"+cpuUse);
}
}
然后用
System.Threading.Thread t = new Thread(new System.Threading.ThreadStart(GetCPUUsage));让其打印出CPU的使用率
可是发现竟然有100%的使用率经常出现,而实际上任务管理器中CPU的使用率从来没有超过5%,严重的不正常。
所以我想问的是,到底怎么样可以异步的读取整台机器的CPU使用率(与任务管理器中的CPU使用率相同)??
------解决思路----------------------
Timer定时执行GetCPUUsage();
------解决思路----------------------
你一个死循环还不想CPU沾满……定期读取就好了,timer也可以。