For a game I’m working on, I wanted to throw the audio on another thread so I could queue up sounds and have them immediately play. The code I’m using in that thread looks like this
private void _checkForThingsToPlay()
{
while (true)
{
if (_song != null)
{
_playSong(_song);
_song = null;
}
while (_effects.Count > 0)
_playSfx(_effects.Dequeue());
Thread.Sleep(100);
}
}
This runs asynchronously and works beautifully. However, without the call to sleep it eats up an entire core on the cpu. My questiom is, is sleep() an efficient way to lower the CPU usage or are there better ways to do this? My friend and I feel like this is a quick hack.
That is called the producer-consumer problem and can be easily solved. If you are using .NET 4, try
BlockingCollection. There’s a good sample code in the MSDN page.Note this line in the sample code:
That will actually block (no CPU cycles wasted) until there is something to consume.