Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

thread get 100% CPU very fast

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)
    {
                
    }
}

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?

Thanks in advance.

like image 409
olidev Avatar asked May 20 '11 00:05

olidev


1 Answers

while (true) is what killing your 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.

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

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.

like image 185
Alex Aza Avatar answered Oct 02 '22 16:10

Alex Aza