0

I'm trying to get cpu load for a background process; Background process

Using Performance Counter

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

It does pretty well on (Apps), but fails on Backgorund returning 0 every time; I'm confused; What's the correct way of retrieving cpu load for thees sort of process?

  • check this example. http://www.codeproject.com/Articles/10258/How-to-get-CPU-usage-of-processes-and-threads – active92 Sep 15 '16 at 08:24
  • There are several instances of that process active, all with the same name. So which one are you actually monitoring? http://stackoverflow.com/a/9115662/17034 – Hans Passant Sep 15 '16 at 08:53
  • I'm running throw all of them, and the result is the same 0 cpu load; ` List prc = runningNow.Where(x => x.ProcessName == txtApp.Text).ToList(); foreach (Process process in prc) {..` – MultyPulty Sep 15 '16 at 08:58

1 Answers1

0

Actually Hans Passant got me a great hint; So the problem is not in background process, but in having multiple instances with the same ProcessName. So in order to create Performance counter you should get process instance name by process id in other words:

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

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