From 5a231cef1507289a2da1c4a719e26b195edccf01 Mon Sep 17 00:00:00 2001 From: Dean Herbert Date: Tue, 8 Dec 2020 15:46:11 +0900 Subject: [PATCH] Add thread safety for external operations on MultiplayerRoom --- .../RealtimeMultiplayer/MultiplayerRoom.cs | 30 ++++++++++++------- 1 file changed, 20 insertions(+), 10 deletions(-) diff --git a/osu.Game/Online/RealtimeMultiplayer/MultiplayerRoom.cs b/osu.Game/Online/RealtimeMultiplayer/MultiplayerRoom.cs index 61320b9d73..7c3724915f 100644 --- a/osu.Game/Online/RealtimeMultiplayer/MultiplayerRoom.cs +++ b/osu.Game/Online/RealtimeMultiplayer/MultiplayerRoom.cs @@ -9,8 +9,6 @@ namespace osu.Game.Online.RealtimeMultiplayer [Serializable] public class MultiplayerRoom { - private object writeLock = new object(); - public long RoomID { get; set; } public MultiplayerRoomState State { get; set; } @@ -31,22 +29,34 @@ namespace osu.Game.Online.RealtimeMultiplayer public MultiplayerRoomUser Join(int userId) { var user = new MultiplayerRoomUser(userId); - lock (writeLock) users.Add(user); + PerformUpdate(_ => users.Add(user)); return user; } public MultiplayerRoomUser Leave(int userId) { - lock (writeLock) + MultiplayerRoomUser user = null; + + PerformUpdate(_ => { - var user = users.Find(u => u.UserID == userId); + user = users.Find(u => u.UserID == userId); - if (user == null) - return null; + if (user != null) + users.Remove(user); + }); - users.Remove(user); - return user; - } + return user; + } + + private object writeLock = new object(); + + /// + /// Perform an update on this room in a thread-safe manner. + /// + /// The action to perform. + public void PerformUpdate(Action action) + { + lock (writeLock) action(this); } } }