From a22dda151e0e20224e5c1b7c84e070982453afac Mon Sep 17 00:00:00 2001 From: Josh Dassinger Date: Sat, 23 Nov 2024 07:47:57 -0600 Subject: [PATCH] Fix threading issues with player name cache --- .../Core/DiscordExtensionCore.PlayerName.cs | 22 +++++++++---------- 1 file changed, 10 insertions(+), 12 deletions(-) diff --git a/Oxide.Ext.Discord/Plugins/Core/DiscordExtensionCore.PlayerName.cs b/Oxide.Ext.Discord/Plugins/Core/DiscordExtensionCore.PlayerName.cs index c71309aa..72279294 100644 --- a/Oxide.Ext.Discord/Plugins/Core/DiscordExtensionCore.PlayerName.cs +++ b/Oxide.Ext.Discord/Plugins/Core/DiscordExtensionCore.PlayerName.cs @@ -1,16 +1,16 @@ +using System.Collections.Concurrent; using System.Collections.Generic; using Oxide.Core.Libraries.Covalence; using Oxide.Core.Plugins; using Oxide.Ext.Discord.Builders; using Oxide.Ext.Discord.Types; -using Oxide.Plugins; namespace Oxide.Ext.Discord.Plugins { internal partial class DiscordExtensionCore { private Plugin _clans; - private readonly Hash> _playerNameCache = new(); + private readonly ConcurrentDictionary> _playerNameCache = new(); // ReSharper disable once UnusedMember.Local [HookMethod(nameof(OnClanCreate))] @@ -39,16 +39,16 @@ private void OnUserNameUpdated(string playerId, string oldName, string newName) { if (oldName != newName) { - foreach (KeyValuePair> cache in _playerNameCache) + foreach (KeyValuePair> cache in _playerNameCache) { - cache.Value.Remove(playerId); + cache.Value.Remove(playerId, out _); } } } private void ClearClanCache() { - foreach (KeyValuePair> cache in _playerNameCache) + foreach (KeyValuePair> cache in _playerNameCache) { if (HasFlag(cache.Key, PlayerDisplayNameMode.Clan)) { @@ -70,15 +70,13 @@ internal string GetClanTag(IPlayer player) public string GetPlayerName(IPlayer player, PlayerDisplayNameMode options) { - Hash cache = _playerNameCache[options]; - if (cache == null) + if (!_playerNameCache.TryGetValue(options, out ConcurrentDictionary cache)) { - cache = new Hash(); + cache = new ConcurrentDictionary(); _playerNameCache[options] = cache; } - string name = cache[player.Id]; - if (!string.IsNullOrEmpty(name)) + if (cache.TryGetValue(player.Id, out string name)) { return name; } @@ -87,7 +85,7 @@ public string GetPlayerName(IPlayer player, PlayerDisplayNameMode options) if (_clans is {IsLoaded: true} && HasFlag(options, PlayerDisplayNameMode.Clan)) { - string clan = _clans.Call("GetClanOf", player.Id); + string clan = GetClanTag(player); if (!string.IsNullOrEmpty(clan)) { sb.Append('['); @@ -110,7 +108,7 @@ public string GetPlayerName(IPlayer player, PlayerDisplayNameMode options) return name; } - private bool HasFlag(PlayerDisplayNameMode options, PlayerDisplayNameMode flag) + private static bool HasFlag(PlayerDisplayNameMode options, PlayerDisplayNameMode flag) { return (options & flag) == flag; }