Skip to content

Commit

Permalink
Use ConcurrentDictionary in NativeGraphicsManager instead of locking …
Browse files Browse the repository at this point in the history
…around regular dictionary
  • Loading branch information
ethanmoffat committed Sep 16, 2022
1 parent 78f3046 commit c47e2d6
Showing 1 changed file with 16 additions and 28 deletions.
44 changes: 16 additions & 28 deletions EOLib.Graphics/NativeGraphicsManager.cs
Original file line number Diff line number Diff line change
@@ -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<LibraryGraphicPair, Texture2D> _cache;
private readonly object __cachelock__ = new object();
private readonly ConcurrentDictionary<LibraryGraphicPair, Texture2D> _cache;

private readonly INativeGraphicsLoader _gfxLoader;
private readonly IGraphicsDeviceProvider _graphicsDeviceProvider;

public NativeGraphicsManager(INativeGraphicsLoader gfxLoader, IGraphicsDeviceProvider graphicsDeviceProvider)
{
_cache = new Dictionary<LibraryGraphicPair, Texture2D>();
_cache = new ConcurrentDictionary<LibraryGraphicPair, Texture2D>();
_gfxLoader = gfxLoader;
_graphicsDeviceProvider = graphicsDeviceProvider;
}
Expand All @@ -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];
}
}

Expand All @@ -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;
}

Expand Down Expand Up @@ -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();
}
}

Expand Down

0 comments on commit c47e2d6

Please sign in to comment.