2014-06-10 53 views
0

我創建了一個新的類測試:爲什麼循環需要這麼長時間和如此緩慢?

using System; 
using System.Collections.Generic; 
using System.Linq; 
using System.Text; 
using OpenHardwareMonitor.Hardware; 
using System.Diagnostics; 
using DannyGeneral; 
using System.Windows.Forms; 
using System.Threading; 
using System.Management; 
using System.Globalization; 
using System.IO; 
using System.Runtime.InteropServices; 

namespace HardwareMonitoring 
{ 


    class CpuUsages 
    { 
     public static string processes; 

     public static string cputest() 
     { 
      PerformanceCounter cpuCounter = new PerformanceCounter(); 
      cpuCounter.CategoryName = "Processor"; 
      cpuCounter.CounterName = "% Processor Time"; 
      cpuCounter.InstanceName = "_Total"; 

      var unused = cpuCounter.NextValue(); // first call will always return 0 
      System.Threading.Thread.Sleep(1000); // wait a second, then try again 
      //Console.WriteLine("Cpu usage: " + cpuCounter.NextValue() + "%"); 
      processes = "Cpu usage: " + cpuCounter.NextValue() + "%"; 
      return processes; 
     } 
    } 
} 

然後在Form1我添加了一個新的計時器設置爲1000毫秒啓用它運行程序時和計時器滴答事件,我沒有內部:

private void timer3_Tick(object sender, EventArgs e) 
     { 
      Process[] processes = Process.GetProcesses(); 

      foreach (Process process in processes) 
      { 
       CpuUsages.cputest(); 
       cpuusage = CpuUsages.processes; 
       label26.Text = cpuusage; 
      } 
     } 

這樣它的工作非常緩慢需要很長時間才能使循環foreach。 通常我想循環每個正在運行的進程並獲得它的cpuusage。

但如果我刪除foreach循環是這樣的:

private void timer3_Tick(object sender, EventArgs e) 
     { 
       Process[] processes = Process.GetProcesses();   
       CpuUsages.cputest(); 
       cpuusage = CpuUsages.processes; 
       label26.Text = cpuusage; 
     } 

然後它會奏效快,我會在label26的cpuusage更新eavery第二看。 問題是它只會顯示進程上的cpuusage。

我能做些什麼來解決它? 通常我想爲列表中的每個進程創建自動數量的標籤並顯示每個進程的cpuusage。但是,當我使用foreach循環時,它非常緩慢並且需要很長時間。

有什麼方法可以解決它嗎?

回答

0

此:

foreach (Process process in processes) 
{ 
    CpuUsages.cputest(); 
    cpuusage = CpuUsages.processes; 
    label26.Text = cpuusage; 
} 

將會使你的程序睡1秒*(你的機器上運行的進程數)。難怪foreach循環很慢。

刪除那些Sleep調用,並讓您的循環在另一個線程中運行,避免減慢用戶界面。

另外我不明白爲什麼你迭代Process.GetProcesses()返回的processes:你沒有使用它們。

+0

quantdev你能告訴我如何做到這一點至少使用過程的一部分? 「我也不明白你爲什麼重複Process.GetProcesses()返回的流程:你沒有使用它們」我想遍歷所有正在運行的進程以獲得每個進程的CPU。我該怎麼做 ? – user3681442

+0

quantdev我必須使用thread.sleep(1000);在新類中如果沒有,它將不會給出正確的CPU使用值/秒。 – user3681442

相關問題