From 00ce9eea620652b97b4d3e8cd9218c6fccff8b1c Mon Sep 17 00:00:00 2001
From: Mary <me@thog.eu>
Date: Tue, 29 Jun 2021 19:37:13 +0200
Subject: Fix disposing of IPC sessions server at emulation stop (#2334)

---
 .../OpenALHardwareDeviceDriver.cs                  | 23 +++++++++++++++-------
 1 file changed, 16 insertions(+), 7 deletions(-)

(limited to 'Ryujinx.Audio.Backends.OpenAL/OpenALHardwareDeviceDriver.cs')

diff --git a/Ryujinx.Audio.Backends.OpenAL/OpenALHardwareDeviceDriver.cs b/Ryujinx.Audio.Backends.OpenAL/OpenALHardwareDeviceDriver.cs
index 387ae772..721e96c6 100644
--- a/Ryujinx.Audio.Backends.OpenAL/OpenALHardwareDeviceDriver.cs
+++ b/Ryujinx.Audio.Backends.OpenAL/OpenALHardwareDeviceDriver.cs
@@ -133,19 +133,28 @@ namespace Ryujinx.Audio.Backends.OpenAL
         {
             if (disposing)
             {
-                lock (_lock)
-                {
-                    _stillRunning = false;
-                    _updaterThread.Join();
+                _stillRunning = false;
 
-                    // Loop against all sessions to dispose them (they will unregister themself)
-                    while (_sessions.Count > 0)
+                int sessionCount = 0;
+
+                // NOTE: This is done in a way to avoid possible situations when the OpenALHardwareDeviceSession is already being dispose in another thread but doesn't hold the lock and tries to Unregister.
+                do
+                {
+                    lock (_lock)
                     {
-                        OpenALHardwareDeviceSession session = _sessions[0];
+                        if (_sessions.Count == 0)
+                        {
+                            break;
+                        }
+
+                        OpenALHardwareDeviceSession session = _sessions[_sessions.Count - 1];
 
                         session.Dispose();
+
+                        sessionCount = _sessions.Count;
                     }
                 }
+                while (sessionCount > 0);
 
                 ALC.DestroyContext(_context);
                 ALC.CloseDevice(_device);
-- 
cgit v1.2.3-70-g09d2