From 6d8bf89f73e43bea8c32447e8b93e86dcd450394 Mon Sep 17 00:00:00 2001 From: Vinzenz Schroeter Date: Tue, 7 May 2024 20:41:21 +0200 Subject: [PATCH] fix concurrent map service access --- tanks-backend/TanksServer/GameLogic/MapService.cs | 10 ++++++---- 1 file changed, 6 insertions(+), 4 deletions(-) diff --git a/tanks-backend/TanksServer/GameLogic/MapService.cs b/tanks-backend/TanksServer/GameLogic/MapService.cs index b9263f4..28a5aef 100644 --- a/tanks-backend/TanksServer/GameLogic/MapService.cs +++ b/tanks-backend/TanksServer/GameLogic/MapService.cs @@ -1,3 +1,4 @@ +using System.Diagnostics; using System.Diagnostics.CodeAnalysis; using System.IO; using DisplayCommands; @@ -13,8 +14,8 @@ internal sealed class MapService public const ushort PixelsPerRow = TilesPerRow * TileSize; public const ushort PixelsPerColumn = TilesPerColumn * TileSize; - private readonly Dictionary _mapPrototypes = new(); - private readonly Dictionary _mapPreviews = new(); + private readonly ConcurrentDictionary _mapPrototypes = new(); + private readonly ConcurrentDictionary _mapPreviews = new(); public IEnumerable MapNames => _mapPrototypes.Keys; @@ -52,7 +53,8 @@ internal sealed class MapService { var name = MapNameFromFilePath(file); var prototype = new SpriteMapPrototype(name, Sprite.FromImageFile(file)); - _mapPrototypes.Add(name, prototype); + var added = _mapPrototypes.TryAdd(name, prototype); + Debug.Assert(added); } private void LoadMapString(string file) @@ -60,7 +62,7 @@ internal sealed class MapService var name = MapNameFromFilePath(file); var map = File.ReadAllText(file).ReplaceLineEndings(string.Empty).Trim(); var prototype = new TextMapPrototype(name, map); - _mapPrototypes.Add(name, prototype); + _mapPrototypes.TryAdd(name, prototype); } private static string MapNameFromFilePath(string filePath) => Path.GetFileName(filePath).ToUpperInvariant();