2016-09-15 93 views
0

我想獲得CPU負載的後臺進程; Background processC#後臺進程CPU負載使用PerformanceCounter

使用性能計數器

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類型的過程?

+0

檢查這個例子

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。 http://www.codeproject.com/Articles/10258/How-to-get-CPU-usage-of-processes-and-threads – active92

+0

該進程有幾個活動實例,都具有相同的名稱。那麼你究竟在監視哪一個? http://stackoverflow.com/a/9115662/17034 –

+0

我正在運行拋出所有這些,結果是相同的0 cpu負載; 'List prc = runningNow.Where(x => x.ProcessName == txtApp.Text).ToList(); foreach(處理過程在prc中) {..' – MultyPulty

回答

0

其實漢斯帕斯特給了我一個很好的提示; 所以這個問題不是在後臺進程中,而是在具有相同ProcessName的多個實例。 所以爲了創建性能計數器,你應該通過進程ID換句話說獲得流程實例名,由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 ..."); 
     }