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

それかなりよく(アプリ)で行いますが、Backgorundは0たびに返すに失敗しました。 私は混乱しています。 プロセスの種類のCPU負荷を取得する正しい方法は何ですか?

+0

によっては、この例を確認してください。 http://www.codeproject.com/Articles/10258/How-to-get-CPU-usage-of-processes-and-threads – active92

+0

そのプロセスのいくつかのインスタンスがあり、すべて同じ名前です。あなたは実際にどのモニタリングをしていますか? http://stackoverflow.com/a/9115662/17034 –

+0

私はそれらのすべてをスローして実行している、結果は同じ0CPUの負荷です。 'リスト prc = runningNow.Where(x => x.ProcessName == txtApp.Text).ToList(); foreach(prcのプロセスプロセス) {..' – MultyPulty

答えて

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

そしてGetProcessInstanceName 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 ..."); 
     } 
関連する問題