From 74ae29503605ff47099554bb0c6cd227592eab49 Mon Sep 17 00:00:00 2001 From: cosmonaut Date: Thu, 29 Jun 2023 15:01:22 -0700 Subject: [PATCH] fix audio thread race condition on StaticAudio.GetInstance --- src/Audio/StaticSound.cs | 31 +++++++++++++++++++++++++------ 1 file changed, 25 insertions(+), 6 deletions(-) diff --git a/src/Audio/StaticSound.cs b/src/Audio/StaticSound.cs index d3ecd252..975af1e8 100644 --- a/src/Audio/StaticSound.cs +++ b/src/Audio/StaticSound.cs @@ -272,22 +272,41 @@ namespace MoonWorks.Audio /// public StaticSoundInstance GetInstance(bool autoFree = true) { - if (AvailableInstances.Count == 0) + StaticSoundInstance instance; + + lock (AvailableInstances) { - AvailableInstances.Push(new StaticSoundInstance(Device, this)); + if (AvailableInstances.Count == 0) + { + AvailableInstances.Push(new StaticSoundInstance(Device, this)); + } + + instance = AvailableInstances.Pop(); } - var instance = AvailableInstances.Pop(); instance.AutoFree = autoFree; - UsedInstances.Add(instance); + + lock (UsedInstances) + { + UsedInstances.Add(instance); + } + return instance; } internal void FreeInstance(StaticSoundInstance instance) { instance.Reset(); - UsedInstances.Remove(instance); - AvailableInstances.Push(instance); + + lock (UsedInstances) + { + UsedInstances.Remove(instance); + } + + lock (AvailableInstances) + { + AvailableInstances.Push(instance); + } } protected override unsafe void Destroy()