如何让线程“报告回主线程”?(How can i make a thread “report back” to main thread?)

编程入门 行业动态 更新时间:2024-10-28 02:31:30
如何让线程“报告回主线程”?(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++; } } }

更多推荐

本文发布于:2023-08-07 05:53:00,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1461609.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:线程   主线   报告   main   thread

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!