openai/openai-dotnet
Publicmirrored from https://github.com/openai/openai-dotnetAvailable
src/Utility/SemaphoreSlimExtensions.cs
58lines · modecode
| 1 | using System; |
| 2 | using System.Diagnostics.Contracts; |
| 3 | using System.Threading; |
| 4 | using System.Threading.Tasks; |
| 5 | |
| 6 | namespace OpenAI; |
| 7 | |
| 8 | internal static class SemaphoreSlimExtensions |
| 9 | { |
| 10 | public static async Task<IDisposable> AutoReleaseWaitAsync( |
| 11 | this SemaphoreSlim semaphore, |
| 12 | CancellationToken cancellationToken = default) |
| 13 | { |
| 14 | Contract.Requires(semaphore != null); |
| 15 | var wrapper = new ReleaseableSemaphoreSlimWrapper(semaphore); |
| 16 | await semaphore.WaitAsync(cancellationToken); |
| 17 | return wrapper; |
| 18 | } |
| 19 | |
| 20 | public static IDisposable AutoReleaseWait( |
| 21 | this SemaphoreSlim semaphore, |
| 22 | CancellationToken cancellationToken = default) |
| 23 | { |
| 24 | Contract.Requires(semaphore != null); |
| 25 | var wrapper = new ReleaseableSemaphoreSlimWrapper(semaphore); |
| 26 | semaphore.Wait(cancellationToken); |
| 27 | return wrapper; |
| 28 | } |
| 29 | |
| 30 | private class ReleaseableSemaphoreSlimWrapper |
| 31 | : IDisposable |
| 32 | { |
| 33 | private readonly SemaphoreSlim semaphore; |
| 34 | private bool alreadyDisposed = false; |
| 35 | |
| 36 | public ReleaseableSemaphoreSlimWrapper(SemaphoreSlim semaphore) |
| 37 | => this.semaphore = semaphore; |
| 38 | |
| 39 | public void Dispose() |
| 40 | { |
| 41 | this.Dispose(true); |
| 42 | GC.SuppressFinalize(this); |
| 43 | } |
| 44 | |
| 45 | protected void Dispose(bool disposeActuallyCalled) |
| 46 | { |
| 47 | if (!this.alreadyDisposed) |
| 48 | { |
| 49 | if (disposeActuallyCalled) |
| 50 | { |
| 51 | this.semaphore?.Release(); |
| 52 | } |
| 53 | |
| 54 | this.alreadyDisposed = true; |
| 55 | } |
| 56 | } |
| 57 | } |
| 58 | } |