openai/openai-dotnet

Public

mirrored from https://github.com/openai/openai-dotnetAvailable

CodeCommitsIssuesPull requestsActionsInsightsSecurity
OpenAI_2.2.0

Branches

Tags

  • No tags available.
0Branches0Tags
Go to file
Add file
Code

Clone

HTTPS

Download ZIP

src/Utility/SemaphoreSlimExtensions.cs

58lines · modecode

1using System;
2using System.Diagnostics.Contracts;
3using System.Threading;
4using System.Threading.Tasks;
5
6namespace OpenAI;
7
8internal 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}