我正在尝试获取特定进程的CPU使用率,但它仅返回0。我仍然不知道问题出在哪里。
Process[] processlist = Process.GetProcesses();
foreach (Process theprocess in processlist)
{
if (GetProcessOwner(theprocess.Id) != "NO_OWNER")
{
if (theprocess.ProcessName != "svchost")
{
var ram = BytesToString(theprocess.PeakWorkingSet64);
ram = ram.Replace("MB", "");
string state = "";
if (theprocess.MainWindowTitle == "")
{
state = "background";
}
else
{
state = "foreground";
}
sw.WriteLine("ID=" + theprocess.Id + "&NAME=" + theprocess.ProcessName + "&RAM=" + ram + "&STARTED=" + theprocess.StartTime + "&STATE=" + state);
PerformanceCounter counter = new PerformanceCounter("Process", "% Processor Time", theprocess.ProcessName);
Console.WriteLine("CPU="+counter.NextValue());
}
}
}
最佳答案
没关系,因为下次调用NextValue时始终返回0。
为了解决此错误,您可以在创建PerformanceCounter对象(耐用性黑客)后两次调用NextValue函数。