diff --git a/src/Impostor.Api/Games/IGame.cs b/src/Impostor.Api/Games/IGame.cs index 4aabe696..093310f1 100644 --- a/src/Impostor.Api/Games/IGame.cs +++ b/src/Impostor.Api/Games/IGame.cs @@ -6,6 +6,7 @@ using Impostor.Api.Innersloth; using Impostor.Api.Innersloth.GameOptions; using Impostor.Api.Net; using Impostor.Api.Net.Inner; +using Impostor.Api.Utils; namespace Impostor.Api.Games { @@ -53,10 +54,10 @@ namespace Impostor.Api.Games T? FindObjectByNetId(uint netId) where T : IInnerNetObject; - /// Lock an IGame to prevent concurrent modification. - /// A that should be awaited before and disposed after modifying the game. + /// Lock an to prevent concurrent modification. + /// A that should be disposed after modifying the game. /// This method should be called when modifying a game outside of an handler. - Task LockAsync(); + ValueTask LockAsync(); /// /// Adds an to the ban list of this game. diff --git a/src/Impostor.Api/Net/LockGuard.cs b/src/Impostor.Api/Net/LockGuard.cs deleted file mode 100644 index 6590853a..00000000 --- a/src/Impostor.Api/Net/LockGuard.cs +++ /dev/null @@ -1,61 +0,0 @@ -using System; -using System.Threading; -using System.Threading.Tasks; - -namespace Impostor.Api.Net -{ - /// RAII-style lock guard for use in Impostor. - /// - /// To lock a semaphore, use the LockAsync method and await the result. - /// To unlock the semaphore, dispose of the LockGuard. - /// - public sealed class LockGuard : IDisposable - { - private readonly SemaphoreSlim _semaphore; - - private bool _disposedValue; - - private LockGuard(SemaphoreSlim semaphore) - { - _semaphore = semaphore; - } - - private void Dispose(bool disposing) - { - if (!_disposedValue) - { - if (disposing) - { - _semaphore.Release(); - } - - _disposedValue = true; - } - } - - /// Create a RAII-style lock guard for an instance of . - /// The semaphore to Wait and Release on. - /// The amount of milliseconds to wait for the lock becoming available. - /// When the timeout expires. - /// The lock guard if the semaphore could be locked succesfully. - public static async Task LockAsync(SemaphoreSlim semaphore, int timeout = 1000) - { - var success = await semaphore.WaitAsync(timeout); - if (success) - { - return new LockGuard(semaphore); - } - else - { - throw new ImpostorException("Could not lock semaphore"); - } - } - - /// - public void Dispose() - { - Dispose(disposing: true); - GC.SuppressFinalize(this); - } - } -} diff --git a/src/Impostor.Api/Utils/AsyncLock.cs b/src/Impostor.Api/Utils/AsyncLock.cs new file mode 100644 index 00000000..0a479855 --- /dev/null +++ b/src/Impostor.Api/Utils/AsyncLock.cs @@ -0,0 +1,71 @@ +using System; +using System.Threading; +using System.Threading.Tasks; + +namespace Impostor.Api.Utils; + +/// +/// Represents an asynchronous lock mechanism. +/// +public sealed class AsyncLock +{ + private readonly SemaphoreSlim _semaphore = new(1, 1); + + /// + /// Asynchronously acquires a lock. + /// + /// + /// A that represents the asynchronous lock operation. + /// The result of the task is a that should be disposed to release the lock. + /// + public ValueTask LockAsync() + { + return LockAsync(CancellationToken.None); + } + + /// + /// The to observe while waiting for the lock. + /// was canceled. + public ValueTask LockAsync(CancellationToken cancellationToken) + { + var wait = _semaphore.WaitAsync(cancellationToken); + + if (wait.IsCompleted) + { + return ValueTask.FromResult(new Releaser(this)); + } + + return new ValueTask(wait.ContinueWith( + static (_, state) => new Releaser((AsyncLock)state!), + this, + cancellationToken, + TaskContinuationOptions.ExecuteSynchronously, + TaskScheduler.Default + )); + } + + /// + /// Represents a disposable object that, when disposed, releases the associated lock. + /// + public struct Releaser : IDisposable + { + private AsyncLock? _lock; + + internal Releaser(AsyncLock @lock) + { + _lock = @lock; + } + + /// + /// Releases the lock held by this instance. + /// + public void Dispose() + { + if (_lock != null) + { + _lock._semaphore.Release(); + _lock = null; + } + } + } +} diff --git a/src/Impostor.Server/Net/State/Game.cs b/src/Impostor.Server/Net/State/Game.cs index 6a8849ae..4ad5ca48 100644 --- a/src/Impostor.Server/Net/State/Game.cs +++ b/src/Impostor.Server/Net/State/Game.cs @@ -4,7 +4,6 @@ using System.Collections.Generic; using System.Diagnostics.CodeAnalysis; using System.Linq; using System.Net; -using System.Threading; using System.Threading.Tasks; using Impostor.Api.Config; using Impostor.Api.Events.Managers; @@ -14,6 +13,7 @@ using Impostor.Api.Innersloth.GameOptions; using Impostor.Api.Net; using Impostor.Api.Net.Manager; using Impostor.Api.Net.Messages.S2C; +using Impostor.Api.Utils; using Impostor.Server.Events; using Impostor.Server.Net.Manager; using Microsoft.Extensions.Logging; @@ -33,7 +33,7 @@ namespace Impostor.Server.Net.State private readonly ICompatibilityManager _compatibilityManager; private readonly CompatibilityConfig _compatibilityConfig; private readonly TimeoutConfig _timeoutConfig; - private readonly SemaphoreSlim _lock; + private readonly AsyncLock _lock = new(); public Game( ILogger logger, @@ -68,7 +68,6 @@ namespace Impostor.Server.Net.State _compatibilityConfig = compatibilityConfig.Value; _timeoutConfig = timeoutConfig.Value; Items = new ConcurrentDictionary(); - _lock = new SemaphoreSlim(1, 1); } public IPEndPoint PublicIp { get; } @@ -116,9 +115,9 @@ namespace Impostor.Server.Net.State return _players.TryGetValue(clientId, out var clientPlayer) ? clientPlayer : null; } - public async Task LockAsync() + public ValueTask LockAsync() { - return await LockGuard.LockAsync(_lock); + return _lock.LockAsync(); } internal async ValueTask StartedAsync()