tgstation-server
The /tg/station 13 server suite
SemaphoreSlimContext.cs
Go to the documentation of this file.
1 using System;
2 using System.Threading;
3 using System.Threading.Tasks;
4 
5 namespace Tgstation.Server.Host.Core
6 {
10  public sealed class SemaphoreSlimContext : IDisposable
11  {
18  public static async Task<SemaphoreSlimContext> Lock(SemaphoreSlim semaphore, CancellationToken cancellationToken)
19  {
20  if (semaphore == null)
21  throw new ArgumentNullException(nameof(semaphore));
22  await semaphore.WaitAsync(cancellationToken).ConfigureAwait(false);
23  cancellationToken.ThrowIfCancellationRequested();
24  return new SemaphoreSlimContext(semaphore);
25  }
26 
30  readonly SemaphoreSlim lockedSemaphore;
31 
35  bool disposed;
36 
41  SemaphoreSlimContext(SemaphoreSlim lockedSemaphore) => this.lockedSemaphore = lockedSemaphore;
42 
46 #pragma warning disable CA1821 // Remove empty Finalizers //TODO remove this when https://github.com/dotnet/roslyn-analyzers/issues/1241 is fixed
47  ~SemaphoreSlimContext() => Dispose();
48 #pragma warning restore CA1821 // Remove empty Finalizers
49 
53  public void Dispose()
54  {
55  lock (this)
56  {
57  if (disposed)
58  return;
59  disposed = true;
60  }
61  GC.SuppressFinalize(this);
62  lockedSemaphore.Release();
63  }
64  }
65 }
readonly SemaphoreSlim lockedSemaphore
The locked SemaphoreSlim
void Dispose()
Release the lock on lockedSemaphore
static async Task< SemaphoreSlimContext > Lock(SemaphoreSlim semaphore, CancellationToken cancellationToken)
Asyncronously locks a semaphore