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.
It is usually a bad habit to use Thread.Sleep()
inside a while(true)
loop. It looks like you have a queue on which you want to push sound effects and you want the "audio thread" to play these effects as soon as they are pushed on the queue. This sounds like a producer/consumer queue. There are multiple ways to build such a queue in C#. You could use Monitor.Wait()
and Monitor.Pulse()
or you could use an AutoResetEvent
object.
In .NET 4 you could also use a BlockingCollection
.
By the way, there is a very good online introduction into threading in C# that describes a lot of common threading/synchronization scenarios and best practices.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With