Threading and sleep ()

For the game I'm working on, I wanted to throw the audio into another stream so that I could queue the sounds and play immediately. The code that I use in this thread is as follows:

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 great. However, without a call to sleep, it feeds on the entire processor core. My quest is sleep () - an effective way to reduce CPU usage, or are there any better ways to do this? My friend and I feel like this is a quick hack.

+4
source share
2 answers

This is called a producer-consumer problem and can be easily solved. If you are using .NET 4, try BlockingCollection . There is a good sample code on the MSDN page.

Pay attention to this line in the sample code:

 while (true) Console.WriteLine(bc.Take()); 

This actually blocks (no CPU cycles in vain) until there is something to consume.

+5
source

Usually a malicious habit is to use Thread.Sleep() inside a while(true) . It looks like you have a queue that you want to click sound effects on, and you want the "audio stream" to play these effects as soon as they are pressed into the queue. It sounds like a lineup of producers / consumers . There are several ways to create such a queue in C #. You can use Monitor.Wait() and Monitor.Pulse() , or you can use an AutoResetEvent object.

In .NET 4, you can also use BlockingCollection .

By the way, there is a very good online introduction to a stream in C # , which describes many common scenarios and best practices for streaming / synchronization.

+7
source

All Articles