C#后台进程使用PerformanceCounter加载cpu

时间:2016-09-15 08:19:15

标签: c# process load cpu performancecounter

我正在尝试为后台进程获取cpu负载; Background process

使用性能计数器

 PerformanceCounter ramCounter = new PerformanceCounter("Process", "Working Set", process.ProcessName);
            PerformanceCounter cpuCounter = new PerformanceCounter("Process", "% Processor Time", process.ProcessName);
            ramCounter.NextValue();
            cpuCounter.NextValue();
            while (true)
            {
                Thread.Sleep(500);
                double ram = ramCounter.NextValue();
                double cpu = cpuCounter.NextValue();
                Console.WriteLine("RAM: " + (ram / 1024 / 1024) + " MB; CPU: " + (cpu) + " %");
            }

它在(Apps)上表现相当不错,但每次Backgorund都返回0时失败; 我糊涂了; 检索cpu负载的正确方法是什么?

1 个答案:

答案 0 :(得分:0)

实际上汉斯帕斯特给了我很大的暗示; 所以问题不在于后台进程,而在于具有相同ProcessName的多个实例。 因此,为了创建性能计数器,您应该按进程ID获取流程实例名称,换句话说:

string processNameYourAreLookingFor ="name";
  List<Process> prc_Aspx = runningNow.Where(x => x.ProcessName == processNameYourAreLookingFor ).ToList();
foreach (Process process in prc_Aspx)
            {

                string _prcName = GetProcessInstanceName(process.Id);
                 new PerformanceCounter("Process", "% Processor Time", _prcName);}
}

按ID

的GetProcessInstanceName
private string GetProcessInstanceName(int pid)
        {
            PerformanceCounterCategory cat = new PerformanceCounterCategory("Process");

            string[] instances = cat.GetInstanceNames();
            foreach (string instance in instances)
            {

                using (PerformanceCounter cnt = new PerformanceCounter("Process",
                     "ID Process", instance, true))
                {
                    int val = (int)cnt.RawValue;
                    if (val == pid)
                    {
                        return instance;
                    }
                }
            }
            throw new Exception("Could not find performance counter " +
                "instance name for current process. This is truly strange ...");
        }