I am employing ThreadPool.QueueUserWorkItem to play some sound files and not hanging up the GUI while doing so.
It is working but has an undesirable side effect.
While the QueueUserWorkItem CallBack Proc is being executed there is nothing to stop it from starting a new thread. This causes the samples in the threads to overlap.
How can I make it so that it waits for the already running thread to finish running and only then run the next request?
EDIT: private object sync = new Object();
lock (sync) {
.......do sound here
}
this works. plays in the sounds in order.
but some samples are getting played more than once when i keep sending sound requests before the one being played ends. will investigate.
EDIT: is the above a result of Lock Convoy @Aaronaught mentioned?
This is a classic thread synchronization issue, where you have multiple clients that all want to use the same resource and need to control how they access it. In this particular case, the sound system is willing to play more than one sound at the same time (and this is often desirable), but since you don’t want that behavior, you can use standard locking to gate access to the sound system:
where Sound is whatever object you’re using to represent a sound to be played. This mechanism is ‘first come, first served’ when multiple sounds vie for play time.
As mentioned in another response, be careful of excessive ‘pile-up’ of sounds, as you’ll start to tie up the ThreadPool.