SemaphoreSlim extension method for safely handling cancellation and disposal

I have often found myself using a try {semaphore.Wait()} finally {semaphore.Release()} pattern when using semaphores, 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
{
{
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 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?

• You should never await the SemaphoreSlim inside the try block. If it throws an exception, you'll end up releasing even though you never acquired a lock. Generally this only matters if the SemaphoreSlim has multiple requests (I see you've limited it at 1). – Brad M Mar 20 at 14:56