2011-12-10 33 views
1

學習C#,WPF。我遇到了一個我無法單靠研究解決的問題。從另一個線程更新另一個類中的文本框內容。 C#,WPF

我想從其他類中存在的另一個線程更新文本框控件的文本。

我知道線程已啓動,正在運行,並且可以使用數據填充文本框。我無法弄清楚的是如何解決第二個線程在GUI中的文本框控件。

我的文本框控件被稱爲'txt_CPU',我想'cpuCount'出現在它裏面。我確信我需要使用委託,但我無法將這些示例與我的代碼聯繫起來。

幫助表示讚賞。 (我確信我的代碼中可能存在其他'問題',這是粗略的學習正在進行中)

所以我們創建了線程。

public MainWindow() 
     { 
      InitializeComponent(); 

      //start a new thread to obtain CPU usage 
      PerformaceClass pc = new PerformaceClass(); 
      Thread pcThread = new Thread(pc.CPUThread); 
      pcThread.Start(); 

     } 

它調用

public class PerformaceClass 
    { 

      public string getCPUUsage() 
      { 
       PerformanceCounter cpuCounter; 

       cpuCounter = new PerformanceCounter(); 

       cpuCounter.CategoryName = "Processor"; 
       cpuCounter.CounterName = "% Processor Time"; 
       cpuCounter.InstanceName = "_Total"; 
       return cpuCounter.RawValue.ToString() + "%"; 

      } 

     public void CPUThread() 
     { 
      PerformaceClass PC = new PerformaceClass(); 

      int i = 0; 
      while (i < 5) 
      { 
       string cpuCount = PC.getCPUUsage(); 
       i++; 
       System.Threading.Thread.Sleep(500); 
       // MessageBox.Show(cpuCount); 

      } 
     } 
    } 

回答

3

一種方法的類是事件處理程序添加到您的PerformaceClass這樣的:

public class PerformanceClass 
{ 
    public event EventHandler<PerformanceEventArgs> DataUpdate; 

    .... 
    public void CPUThread() 
    { 
     int i = 0; 
     while (i++ < 5) 
     { 
      string cpuCount = getCPUUsage(); 
      OnDataUpdate(cpuCount); 
      System.Threading.Thread.Sleep(500); 

     } 
    } 

    private void OnDataUpdate(string data) 
    { 
      var handler = DataUpdate; 
      if (handler != null) 
      { 
       handler(this, new PerformanceEventArgs(data)); 
      } 
    } 
} 

public class PerformanceEventArgs: EventArgs 
{ 
     public string Data { get; private set; } 
     public PerformanceEventArgs(string data) 
     { 
      Data = data; 
     } 
} 

然後用它在你的主是這樣的:

public MainWindow() 
{ 
    InitializeComponent(); 

    //start a new thread to obtain CPU usage 
    PerformanceClass pc = new PerformanceClass(); 
    pc.DataUpdate += HandleDataUpdate; 
    Thread pcThread = new Thread(pc.CPUThread); 
    pcThread.Start(); 
} 

private void HandleDataUpdate(object sender, PerformanceEventArgs e) 
{ 
    // dispatch the modification to the text box to the UI thread (main window dispatcher) 
    Dispatcher.BeginInvoke(DispatcherPriority.Normal,() => { txt_CPU.Text = e.Data }); 
} 

請注意,我修復了輸入PerformanceClass(缺少n)。

相關問題