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