From abbc40f29936ce7f9e7b6177a4b1b19adb82921e Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Franti=C5=A1ek=20Boh=C3=A1=C4=8Dek?= Date: Sun, 26 Dec 2021 23:05:13 +0100 Subject: [PATCH] feat: add semaphore to game --- Core/NosSmooth.Game/Game.cs | 45 ++++++++++++++++++++++++------------- 1 file changed, 30 insertions(+), 15 deletions(-) diff --git a/Core/NosSmooth.Game/Game.cs b/Core/NosSmooth.Game/Game.cs index a2ee239..baa4d49 100644 --- a/Core/NosSmooth.Game/Game.cs +++ b/Core/NosSmooth.Game/Game.cs @@ -5,12 +5,9 @@ // Licensed under the MIT license. See LICENSE file in the project root for full license information. using Microsoft.Extensions.Options; -using Microsoft.Extensions.Primitives; -using NosSmooth.Game.Data.Chat; -using NosSmooth.Game.Data.Inventory; +using NosSmooth.Game.Data.Characters; +using NosSmooth.Game.Data.Maps; using NosSmooth.Game.Data.Raids; -using NosSmooth.Game.Entities; -using NosSmooth.Game.Maps; namespace NosSmooth.Game; @@ -19,8 +16,8 @@ namespace NosSmooth.Game; /// public class Game { - private Map? _currentMap; private readonly GameOptions _options; + private Map? _currentMap; /// /// Initializes a new instance of the class. @@ -52,11 +49,6 @@ public class Game } } - /// - /// Gets the friends list of the current client. - /// - public IReadOnlyList? Friends { get; internal set; } - /// /// Gets the active raid the client is currently on. /// @@ -66,12 +58,35 @@ public class Game public Raid? CurrentRaid { get; internal set; } /// - /// Gets the inventory of the client character. + /// Cancellation token for changing the map to use in memory cache. /// - public Inventory Inventory { get; internal set; } + internal CancellationTokenSource? MapChanged { get; private set; } /// - /// Cancellation token for changing the map to use in memory cache. + /// Gets the set semaphore used for changing internal fields. /// - internal CancellationTokenSource? MapChanged { get; private set; } + internal SemaphoreSlim SetSemaphore { get; } = new SemaphoreSlim(1, 1); + + /// + /// Ensures that Character is not null. + /// + /// Whether to release the semaphore. + /// The cancellation token for cancelling the operation. + /// A Task that may or may not have succeeded. + internal async Task EnsureCharacterCreatedAsync(bool releaseSemaphore, CancellationToken ct = default) + { + await SetSemaphore.WaitAsync(ct); + Character? character = Character; + if (Character is null) + { + Character = character = new Character(); + } + + if (releaseSemaphore) + { + SetSemaphore.Release(); + } + + return character!; + } } \ No newline at end of file -- 2.48.1