使用PerformanceCounter获取进程的CPU使用率

时间:2014-01-18 16:05:18

标签: c# process cpu performancecounter

我正在尝试获取特定进程的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());
        }
    }
}

1 个答案:

答案 0 :(得分:1)

没关系,因为 NextValue在第一次调用时总是返回0

要修复此错误,您可以在创建PerformanceCounter对象(durty hack)后调用NextValue函数两次。