Thread gets 100% processor very fast

I use a very simple stream 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 a 100% processor. I want to check if sensor data is read inside a while (true) loop. Why is this so?

Thanks in advance.

+6
source share
5 answers

while (true) is what kills your processor.

You can add Thread.Sleep(X) to you to give the CPU a little rest before checking again.

It also seems like you really need a timer.

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

Use a timer with a maximum pull-out interval, as you can afford, 1 second, half a second.
You need a trade-off between CPU usage and the maximum latency you can afford between checks.

+12
source

Let your cycle be asleep. He runs around and gets tired. At least let it take a break after all.

+2
source

Since your function does nothing inside the while block, it captures the processor and, for practical reasons, never releases it, so other threads can do their job.

 private void checkingData() { while (true) { // executes, immediately } } 

If you change it to the following, you will see more reasonable CPU consumption:

 private void checkingData() { while (true) { // read your sensor data Thread.Sleep(1000); } } 
+1
source

you can use a blocking queue. taking an item from the blocking queue will block the thread until the item is queued. which does not require any processor.

with .net4, you can use BlockingCollection http://msdn.microsoft.com/en-us/library/dd267312.aspx

in version 4, the int.net framework queue is not blocked.

You can find many queue blocking tools if you google it.

here is the implementation

http://www.codeproject.com/KB/recipes/boundedblockingqueue.aspx

By the way

. where do the data you expect come from?

EDIT

if you want to check the file. you can use FileSystemWatcher to check it with a stream block.

if your data comes from an external API and the api does not block the thread, it is impossible to block the thread except using Thread.Sleep

0
source

If you are conducting a survey for a condition, be sure to do as others suggested and fall asleep. I will also add that if you need maximum performance, you can use a statistical trick to avoid sleep when the sensor data has been read. When you find that the sensor data is idle, say, 10 times in a row, then start to sleep again at each iteration.

0
source

Source: https://habr.com/ru/post/888604/


All Articles