Im making a app that monitors stuff on my computer, and i want to make it somewhat more difficult then just implementing a while loop.
So my question is how do i do it if i would like to fetch cpu load in a seperate thread, that updates a static variable in class
namespace threads
{
class Program
{
static int cpuload = 0;
static void Main(string[] args)
{
while (true)
{
Thread th = new Thread(new ThreadStart(CheckCPULoad));
th.Start();
Thread.Sleep(1000); // sleep the main thread
th.Abort();
Console.WriteLine("load: {0}%", cpuload);
}
}
static void CheckCPULoad()
{
// things are updated every 3 secs, dummy data
Thread.Sleep(3000);
Random rnd = new Random();
cpuload++;// = rnd.Next(0, 100); // dummy data
}
}
}
As it is "load: 0%" is printed every time. what do i need to fix to make it show
load: 0%
load: 0%
load: 0%
?
thanks
In order to "report back" to the main thread, the main thread has to be "listening". Which means, still running in a while loop and checking some kind of a queue for new items that represent the reports.
What you basically need is a queue where the worker thread will put its reports, and the main thread will periodically check this queue for reports from the worker.
You have two main approaches:
If your application is a UI application you automatically get the first approach, as this is how the UI works. To add "an item" you can use Control.BeginInvoke (in winforms) or Dispatcher.BeginInvoke (in wpf).
If i get you right, this should solve your purpose. Notice the while loop inside the CheckCPULoad()
method.
class Program
{
static int cpuload = 0;
static void Main(string[] args)
{
Thread th = new Thread(new ThreadStart(CheckCPULoad));
th.Start();
while (true)
{
Thread.Sleep(1000);
Console.WriteLine("load: {0}%", cpuload);
}
th.Abort(); // Don't ever reach this line with while (true)
}
static void CheckCPULoad()
{
while (true)
{
Thread.Sleep(3000);
cpuload++;
}
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With