如何让线程“报告回主线程”?(How can i make a thread “report back” to main thread?)
我正在制作一个应用程序,监视我的计算机上的东西,我想让它更难以实现一个while循环。
所以我的问题是如果我想在一个单独的线程中获取cpu加载,如何在类中更新静态变量,我该怎么做
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 } } }因为每次都打印“load:0%”。 我需要修复什么才能让它显示出来
load: 0% load: 0% load: 0%?
谢谢
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
最满意答案
如果我找对你,这应该可以解决你的目的。 注意CheckCPULoad()方法中的while循环。
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 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++; } } }更多推荐
发布评论