1

I wrote a .NET app that spawns a thread that loops endlessly as it checks to make sure that some conditions are true. Task Manager reveals that the moment this thread is spawned, the application uses almost all the CPU resources available, for as long as the thread runs, which is the lifetime of the application.

How can this thread be prevented from using so much CPU resources?

John Smith
  • 4,416
  • 7
  • 41
  • 56

2 Answers2

3

The best way to prevent consuming CPU is to wait until the desired condition is true. Use some kind of synchronization primitive to coordinate your threads. An event would be a good start.

usr
  • 168,620
  • 35
  • 240
  • 369
1

Use Monitors if you have to wait for data from other threads: http://msdn.microsoft.com/de-de/library/system.threading.monitor%28v=vs.80%29.aspx

if that's not possible, you can consider adding a sleep of, for example 10ms, within the while loop. This should help.

while(true) {
     //Do something here
     Thread.Sleep(10); //Don't consume whole CPU
}

See also the following related post: Thread.Sleep or Thread.Yield

Community
  • 1
  • 1
Stefan Profanter
  • 6,458
  • 6
  • 41
  • 73
  • Sleep() loops like this introduce an average 5ms latency on checking 'some conditions' and still waste some CPU. In 99.9% of all inter-thread comms, it should be replaced by inter-thread signaling via kernel synchro mechanisms, (as suggested by usr). I'm not downvoting 'cos it will work, (badly), and because of the 0.1% where there is no choice. – Martin James Nov 23 '12 at 00:46