【发布时间】:2014-01-18 16:05:18
【问题描述】:
我正在尝试获取特定进程的 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());
}
}
}
【问题讨论】:
-
只是想知道您是否为
p.ProcessName创建了一个对象。我试图复制并粘贴它,但它没有被定义。 -
@puretppc 编辑了我的问题。
-
第一次调用 NextValue() 初始化计数器。然后你之后重复调用它,相隔一秒,然后你在最后一秒得到使用。必须等待那一秒很重要,您可以使用计时器。
标签: c# process cpu performancecounter