namespace ModelContextProtocol;
internal static class SynchronizationExtensions
{
///
/// Asynchronously acquires a lock on the semaphore and returns a disposable object that releases the lock when disposed.
///
/// The semaphore to acquire a lock on.
/// A cancellation token to observe while waiting for the semaphore.
/// A disposable that releases the semaphore when disposed.
///
/// This extension method provides a convenient pattern for using a semaphore in asynchronous code,
/// similar to how the `lock` statement is used in synchronous code.
///
/// The was canceled.
public static async ValueTask LockAsync(this SemaphoreSlim semaphore, CancellationToken cancellationToken = default)
{
await semaphore.WaitAsync(cancellationToken).ConfigureAwait(false);
return new(semaphore);
}
///
/// A disposable struct that releases a semaphore when disposed.
///
///
/// This struct is used with the extension method to provide
/// a using-pattern for semaphore locking, similar to lock statements.
///
public readonly struct Releaser(SemaphoreSlim semaphore) : IDisposable
{
///
/// Releases the semaphore.
///
///
/// This method is called automatically when the goes out of scope
/// in a using statement or expression.
///
public void Dispose() => semaphore.Release();
}
}