Learning C#, WPF. I’ve come across a problem I can’t solve by research alone.
I want to update the text of a textbox control from another thread which is present in another class.
I know the thread is started, working and has data I can use to populate the text box. What I can’t figure out is how to address the text box control in the GUI from the second thread.
My text box control is called ‘txt_CPU’ and I want ‘cpuCount’ to appear in it. I’m sure I need to use delegation, but I can’t relate the examples to my code.
Help is appreciated. (I’m sure there are may other ‘problems’ in my code, this is rough learning in progress)
So we have the thread creation.
public MainWindow()
{
InitializeComponent();
//start a new thread to obtain CPU usage
PerformaceClass pc = new PerformaceClass();
Thread pcThread = new Thread(pc.CPUThread);
pcThread.Start();
}
The Class it’s calling
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);
}
}
}
One way is to add an event handler to your
PerformaceClasslike this:Then use it in your main like this:
Note that I fixed the typo in the
PerformanceClass(missingn).