From c47e2d668e9e34e0a3b225353e60bb06a8b064fd Mon Sep 17 00:00:00 2001 From: Ethan Moffat Date: Fri, 16 Sep 2022 12:43:00 -0700 Subject: [PATCH] Use ConcurrentDictionary in NativeGraphicsManager instead of locking around regular dictionary --- EOLib.Graphics/NativeGraphicsManager.cs | 44 +++++++++---------------- 1 file changed, 16 insertions(+), 28 deletions(-) diff --git a/EOLib.Graphics/NativeGraphicsManager.cs b/EOLib.Graphics/NativeGraphicsManager.cs index d9e9b1939..d2383ef99 100644 --- a/EOLib.Graphics/NativeGraphicsManager.cs +++ b/EOLib.Graphics/NativeGraphicsManager.cs @@ -1,28 +1,26 @@ -using System; -using System.Collections.Generic; -using System.IO; -using AutomaticTypeMapper; +using AutomaticTypeMapper; using Microsoft.Xna.Framework.Graphics; using SixLabors.ImageSharp; using SixLabors.ImageSharp.Drawing.Processing; -using SixLabors.ImageSharp.Formats.Png; using SixLabors.ImageSharp.PixelFormats; using SixLabors.ImageSharp.Processing; +using System; +using System.Collections.Concurrent; +using System.IO; namespace EOLib.Graphics { [MappedType(BaseType = typeof(INativeGraphicsManager), IsSingleton = true)] public sealed class NativeGraphicsManager : INativeGraphicsManager { - private readonly Dictionary _cache; - private readonly object __cachelock__ = new object(); + private readonly ConcurrentDictionary _cache; private readonly INativeGraphicsLoader _gfxLoader; private readonly IGraphicsDeviceProvider _graphicsDeviceProvider; public NativeGraphicsManager(INativeGraphicsLoader gfxLoader, IGraphicsDeviceProvider graphicsDeviceProvider) { - _cache = new Dictionary(); + _cache = new ConcurrentDictionary(); _gfxLoader = gfxLoader; _graphicsDeviceProvider = graphicsDeviceProvider; } @@ -33,17 +31,16 @@ public Texture2D TextureFromResource(GFXTypes file, int resourceVal, bool transp var key = new LibraryGraphicPair((int)file, 100 + resourceVal); - lock (__cachelock__) + if (_cache.ContainsKey(key)) { - if (!reloadFromFile && _cache.ContainsKey(key)) + if (reloadFromFile) { - return _cache[key]; + _cache[key]?.Dispose(); + _cache.TryRemove(key, out var _); } - - if (_cache.ContainsKey(key) && reloadFromFile) + else { - if (_cache[key] != null) _cache[key].Dispose(); - _cache.Remove(key); + return _cache[key]; } } @@ -64,11 +61,7 @@ public Texture2D TextureFromResource(GFXTypes file, int resourceVal, bool transp } } - lock (__cachelock__) - { - _cache.Add(key, ret); - } - + _cache.TryAdd(key, ret); return ret; } @@ -103,14 +96,9 @@ private static void CrossPlatformMakeTransparent(Image bmp, Color transparentCol public void Dispose() { - lock (__cachelock__) - { - foreach (var text in _cache.Values) - { - text.Dispose(); - } - _cache.Clear(); - } + foreach (var text in _cache.Values) + text.Dispose(); + _cache.Clear(); } }