| | 1 | | // Copyright (c) ZeroC, Inc. |
| | 2 | |
|
| | 3 | | namespace IceRpc.Internal; |
| | 4 | |
|
| | 5 | | internal static class SemaphoreSlimExtensions |
| | 6 | | { |
| | 7 | | /// <summary>Acquires a semaphore lock. The acquisition waits to enter the semaphore and returns a lock that will |
| | 8 | | /// release the semaphore when disposed.</summary> |
| | 9 | | /// <param name="semaphore">The semaphore.</param> |
| | 10 | | /// <returns>The semaphore lock.</returns> |
| | 11 | | internal static SemaphoreLock Acquire(this SemaphoreSlim semaphore) |
| | 12 | | { |
| | 13 | | semaphore.Wait(); |
| | 14 | | return new SemaphoreLock(semaphore); |
| | 15 | | } |
| | 16 | |
|
| | 17 | | /// <summary>Acquires a semaphore lock. The acquisition waits to enter the semaphore and returns a lock that will |
| | 18 | | /// release the semaphore when disposed.</summary> |
| | 19 | | /// <param name="semaphore">The semaphore.</param> |
| | 20 | | /// <param name="cancellationToken">A cancellation token that receives the cancellation requests.</param> |
| | 21 | | /// <returns>The semaphore lock.</returns> |
| | 22 | | internal static async ValueTask<SemaphoreLock> AcquireAsync( |
| | 23 | | this SemaphoreSlim semaphore, |
| | 24 | | CancellationToken cancellationToken) |
| | 25 | | { |
| | 26 | | await semaphore.WaitAsync(cancellationToken).ConfigureAwait(false); |
| | 27 | | return new SemaphoreLock(semaphore); |
| | 28 | | } |
| | 29 | | } |
| | 30 | |
|
| | 31 | | /// <summary>A simple helper for releasing a semaphore.</summary> |
| | 32 | | /// <remarks>The caller must be extremely careful to call Dispose at most once.</remarks> |
| | 33 | | internal readonly struct SemaphoreLock : IDisposable |
| | 34 | | { |
| | 35 | | private readonly SemaphoreSlim _semaphore; |
| | 36 | |
|
| 5638 | 37 | | public void Dispose() => _semaphore.Release(); |
| | 38 | |
|
| 5638 | 39 | | internal SemaphoreLock(SemaphoreSlim semaphore) => _semaphore = semaphore; |
| | 40 | | } |