~ruther/NosSmooth

ref: 2023.12 NosSmooth/Core/NosSmooth.Game/GameSemaphores.cs -rw-r--r-- 1.5 KiB
58d87434 — Rutherther chore: bump versions 2 years ago
                                                                                
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
//
//  GameSemaphores.cs
//
//  Copyright (c) František Boháček. All rights reserved.
//  Licensed under the MIT license. See LICENSE file in the project root for full license information.

namespace NosSmooth.Game;

/// <summary>
/// Holds information about semaphores for synchornizing the game packet data.
/// </summary>
internal class GameSemaphores
{
    private Dictionary<GameSemaphoreType, SemaphoreSlim> _semaphores;

    /// <summary>
    /// Initializes a new instance of the <see cref="GameSemaphores"/> class.
    /// </summary>
    public GameSemaphores()
    {
        _semaphores = new Dictionary<GameSemaphoreType, SemaphoreSlim>();
        foreach (var type in Enum.GetValues(typeof(GameSemaphoreType)).Cast<GameSemaphoreType>())
        {
            _semaphores[type] = new SemaphoreSlim(1, 1);
        }
    }

    /// <summary>
    /// Acquire the given semaphore.
    /// </summary>
    /// <param name="semaphoreType">The semaphore type.</param>
    /// <param name="ct">The cancellation token for cancelling the operation.</param>
    /// <returns>A task that may or may not have succeeded.</returns>
    public Task AcquireSemaphore(GameSemaphoreType semaphoreType, CancellationToken ct = default)
    {
        return _semaphores[semaphoreType].WaitAsync(ct);
    }

    /// <summary>
    /// Release the acquired semaphore.
    /// </summary>
    /// <param name="semaphoreType">The semaphore type.</param>
    public void ReleaseSemaphore(GameSemaphoreType semaphoreType)
    {
        _semaphores[semaphoreType].Release();
    }
}
Do not follow this link