openai/openai-dotnet

Public

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

CodeCommitsIssuesPull requestsActionsInsightsSecurity
OpenAI_2.4.0

Branches

Tags

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

Clone

HTTPS

Download ZIP

src/Utility/SemaphoreSlimExtensions.cs

58lines · modeblame

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