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 · modepreview

using System;
using System.Diagnostics.Contracts;
using System.Threading;
using System.Threading.Tasks;

namespace OpenAI;

internal static class SemaphoreSlimExtensions
{
    public static async Task<IDisposable> AutoReleaseWaitAsync(
        this SemaphoreSlim semaphore,
        CancellationToken cancellationToken = default)
    {
        Contract.Requires(semaphore != null);
        var wrapper = new ReleaseableSemaphoreSlimWrapper(semaphore);
        await semaphore.WaitAsync(cancellationToken);
        return wrapper;
    }

    public static IDisposable AutoReleaseWait(
        this SemaphoreSlim semaphore,
        CancellationToken cancellationToken = default)
    {
        Contract.Requires(semaphore != null);
        var wrapper = new ReleaseableSemaphoreSlimWrapper(semaphore);
        semaphore.Wait(cancellationToken);
        return wrapper;
    }

    private class ReleaseableSemaphoreSlimWrapper
        : IDisposable
    {
        private readonly SemaphoreSlim semaphore;
        private bool alreadyDisposed = false;

        public ReleaseableSemaphoreSlimWrapper(SemaphoreSlim semaphore)
            => this.semaphore = semaphore;

        public void Dispose()
        {
            this.Dispose(true);
            GC.SuppressFinalize(this);
        }

        protected void Dispose(bool disposeActuallyCalled)
        {
            if (!this.alreadyDisposed)
            {
                if (disposeActuallyCalled)
                {
                    this.semaphore?.Release();
                }

                this.alreadyDisposed = true;
            }
        }
    }
}