2016-03-01 15 views
0

我有一個WPF應用程序,我想從應用程序中提供CPU使用情況詳細信息(應用程序自身報告)。我有一個工作控制檯應用程序,允許我監視任何應用程序,我想知道是否可以使用PerformanceCounter的此相同邏輯更新LabelTextBox以及來自PerformanceCounter的信息。爲WPF應用程序中的標籤分配PerformanceCounter的值?

代碼CPU使用率 - 控制檯應用程序:

static void Main(string[] args) 
    { 
     Console.WriteLine("Please enter a Application to monitor"); 
     appName = Console.ReadLine(); 

     PerformanceCounter myAppCPU = 
     new PerformanceCounter("Process", "% Processor Time", appName, true); 

     Console.WriteLine("Press the any key to stop ... \n"); 

     if (myAppCPU != null) 
     { 
      while (!Console.KeyAvailable) 
      { 
       double pct = myAppCPU.NextValue(); 
       Console.WriteLine("CPU % = " + pct); 
       Thread.Sleep(2500); 
      } 
     } 
     else 
      Console.WriteLine("No Process found"); 
    } 
+0

也許我沒有看到實際的問題是什麼,但是您可以在WPF項目中獲得'PerformanceCounter'值,並將值提供給'UI'。是否有一個特定的原因,您無法/看到您無法將價值提升到用戶界面? –

+0

@StephenRoss,謝謝你的回覆。我想弄清楚如何在我的應用程序中顯示原始CPU使用情況信息 –

回答

1
//Create the Performance Counter for the current Process 
    PerformanceCounter myAppCPU = new PerformanceCounter("Process", "% Processor Time", Process.GetCurrentProcess().ProcessName, true); 

    public MainWindow() 
    { 
     InitializeComponent(); 

     //Initialize a timer 
     System.Windows.Threading.DispatcherTimer dispatcherTimer = new System.Windows.Threading.DispatcherTimer(); 
     dispatcherTimer.Tick += DispatcherTimer_Tick; 
     //Check the CPU every 3 seconds 
     dispatcherTimer.Interval = new TimeSpan(0, 0, 3); 
     //Start the Timer 
     dispatcherTimer.Start(); 
    } 

    //Every 3 seconds the timer ticks 
    private void DispatcherTimer_Tick(object sender, EventArgs e) 
    { 
     //Write the result to the content of a label (CPULabel) 
     CPULabel.Content = $"CPU % = {myAppCPU.NextValue()}"; 
    } 

隨着Process.GetCurrentProcess().ProcessName你可以得到你的應用程序的進程名 。

創建一個計時器,每隔x秒鐘計時一次。在Timer事件中,讀取下一個CPU值並將其直接寫入標籤(如我的示例中)或綁定到您查看的屬性。