I have often found myself using a try {semaphore.Wait()} finally {semaphore.Release()}
pattern when using a semaphore, so decided I wanted to try and write an extension method to do this instead.
This stems from the problem where I wanted to dispose of my class containing the SemaphoreSlim
instance, and was unsure how to safely and elegantly deal with the SemaphoreSlim
instance as well. I'm still not sure if this is the right approach:
public static class SemaphoreSlimExtension
{
public static async Task RunAsync(this System.Threading.SemaphoreSlim semaphore, Func<Task> action, System.Threading.CancellationToken cancellationToken)
{
try
{
cancellationToken.ThrowIfCancellationRequested();
try
{
await semaphore.WaitAsync(cancellationToken);
await action();
}
finally
{
semaphore.Release();
}
}
catch (OperationCanceledException ex)
{
if (cancellationToken != ex.CancellationToken || !cancellationToken.IsCancellationRequested)
{
throw;
}
}
catch (ObjectDisposedException ex)
{
if (!cancellationToken.IsCancellationRequested)
{
throw;
}
}
}
}
Example usage:
public class ClassA : IDisposable
{
private CancellationTokenSource WorkSemaphoreCancellationTokenSource { get; } = new CancellationTokenSource();
private SemaphoreSlim WorkSemaphore { get; } = new SemaphoreSlim(1, 1);
public async Task DoWork()
{
await WorkSemaphore.RunAsync(() => Task.Delay(5000), WorkSemaphoreCancellationTokenSource.Token);
}
public void Dispose()
{
WorkSemaphoreCancellationTokenSource.Cancel();
WorkSemaphore.Dispose();
WorkSemaphoreCancellationTokenSource.Dispose();
}
}
Does this seem like a good approach? Is there a better way to safely manage the cancellation and disposal of SemaphoreSlim
instances?
await
theSemaphoreSlim
inside thetry
block. If it throws an exception, you'll end up releasing even though you never acquired a lock. Generally this only matters if theSemaphoreSlim
has multiple requests (I see you've limited it at 1). \$\endgroup\$