【问题标题】:C# Background process cpu load using PerformanceCounterC#后台进程cpu负载使用PerformanceCounter
【发布时间】:2016-09-15 08:19:15
【问题描述】:

我正在尝试为后台进程获取 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) + " %");
            }

它在(应用程序)上表现不错,但在 Backgorund 每次都返回 0 时失败; 我很困惑; 为这些进程检索 CPU 负载的正确方法是什么?

【问题讨论】:

  • 检查这个例子。 codeproject.com/Articles/10258/…
  • 该进程的多个实例处于活动状态,它们都具有相同的名称。那么您实际监控的是哪一个? stackoverflow.com/a/9115662/17034
  • 我正在运行 throw 所有这些,结果是相同的 0 cpu 负载; ` List prc = runningNow.Where(x => x.ProcessName == txtApp.Text).ToList(); foreach(在 prc 中的进程){..`

标签: c# process load cpu performancecounter


【解决方案1】:

实际上,Hans Passant 给了我一个很好的暗示; 所以问题不在于后台进程,而在于有多个具有相同 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);}
}

还有 GetProcessInstanceName by id

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 ...");
        }

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2011-03-25
    • 1970-01-01
    • 2014-11-28
    • 2023-01-31
    • 2018-02-05
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多