tgstation-server 6.12.0
The /tg/station 13 server suite
Loading...
Searching...
No Matches
SemaphoreSlimContext.cs
Go to the documentation of this file.
1using System;
2using System.Threading;
3using System.Threading.Tasks;
4
5using Microsoft.Extensions.Logging;
6
8{
13 {
21 public static async ValueTask<SemaphoreSlimContext> Lock(SemaphoreSlim semaphore, CancellationToken cancellationToken, ILogger? logger = null)
22 {
23 ArgumentNullException.ThrowIfNull(semaphore);
24 logger?.LogTrace("Acquiring semaphore...");
25 await semaphore.WaitAsync(cancellationToken);
26 return new SemaphoreSlimContext(semaphore, logger);
27 }
28
36 public static SemaphoreSlimContext? TryLock(SemaphoreSlim semaphore, ILogger? logger, out bool locked)
37 {
38 ArgumentNullException.ThrowIfNull(semaphore);
39 logger?.LogTrace("Trying to acquire semaphore...");
40 locked = semaphore.Wait(TimeSpan.Zero);
41 logger?.LogTrace("Acquired semaphore {un}successfully", locked ? String.Empty : "un");
42 return locked
43 ? new SemaphoreSlimContext(semaphore, logger)
44 : null;
45 }
46
50 readonly ILogger? logger;
51
55 readonly SemaphoreSlim lockedSemaphore;
56
63 {
64 this.lockedSemaphore = lockedSemaphore;
65 this.logger = logger;
66 }
67
71 public void Dispose()
72 {
73 logger?.LogTrace("Releasing semaphore...");
74 lockedSemaphore.Release();
75 }
76 }
77}
readonly? ILogger logger
An optional ILogger to write to.
readonly SemaphoreSlim lockedSemaphore
The locked SemaphoreSlim.
SemaphoreSlimContext(SemaphoreSlim lockedSemaphore, ILogger? logger)
Initializes a new instance of the SemaphoreSlimContext class.
static async ValueTask< SemaphoreSlimContext > Lock(SemaphoreSlim semaphore, CancellationToken cancellationToken, ILogger? logger=null)
Asyncronously locks a semaphore .
static ? SemaphoreSlimContext TryLock(SemaphoreSlim semaphore, ILogger? logger, out bool locked)
Asyncronously attempts to lock a semaphore .
void Dispose()
Release the lock on lockedSemaphore.