线程非常快地获得100%CPU [英] thread get 100% CPU very fast

查看:99
本文介绍了线程非常快地获得100%CPU的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在C#中实现一个非常基本的线程:

I am implementing a very basic thread in C#:

private Thread listenThread;

public void startParser()
{
   this.listenThread = new Thread(new ThreadStart(checkingData));
   this.listenThread.IsBackground = true;
   this.listenThread.Start();
}

private void checkingData()
{
   while (true)
   {

   }

}

然后我立即获得100%的CPU.我想检查是否在while(true)循环内读取了传感器数据.为什么会这样?

Then I immediately get 100% CPU. I want to check if sensor data is read inside the while(true) loop. Why it is like this?

先谢谢了.

推荐答案

while (true)是杀死CPU的原因.

while (true) is what killing your CPU.

您可以在添加Thread.Sleep(X)的同时为CPU提供一些休息,然后再进行检查.

You can add Thread.Sleep(X) to you while to give CPU some rest before checking again.

另外,似乎您实际上需要一个计时器.

Also, seems like you actually need a Timer.

在此处查看计时器类之一 http://msdn.microsoft.com/zh-CN/library/system.threading.timer.aspx .

Look at one of the Timer classes here http://msdn.microsoft.com/en-us/library/system.threading.timer.aspx.

以尽可能高的拉拔间隔使用计时器,即1秒半秒.
您需要在CPU使用率和两次检查之间可以承受的最大延迟之间进行权衡.

Use Timer with as high pulling interval as you can afford, 1 sec, half a sec.
You need to tradeoff between CPU usage and the maximum delay you can afford between checks.

这篇关于线程非常快地获得100%CPU的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆