Skip to content

Commit

Permalink
Added SemaphoreSlim extension methods
Browse files Browse the repository at this point in the history
  • Loading branch information
devedse committed Jan 16, 2020
1 parent 308d627 commit 4f1cf9b
Showing 1 changed file with 50 additions and 0 deletions.
50 changes: 50 additions & 0 deletions DeveCoolLib/Threading/SemaphoreSlimExtensions.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,50 @@
using System;
using System.Threading;
using System.Threading.Tasks;

namespace DeveCoolLib.Threading
{
public static class SemaphoreSlimExtensions
{
public static async Task RunAsync(this SemaphoreSlim semaphore, Func<Task> action, CancellationToken cancellationToken = default)
{
await semaphore.WaitAsync(cancellationToken);

try
{
await action();
}
finally
{
semaphore.Release();
}
}

public static SemaphoreDisposer DisposableWait(this SemaphoreSlim semaphore, CancellationToken cancellationToken = default)
{
semaphore.Wait(cancellationToken);
return new SemaphoreDisposer(semaphore);
}

public static async Task<SemaphoreDisposer> DisposableWaitAsync(this SemaphoreSlim semaphore, CancellationToken cancellationToken = default)
{
await semaphore.WaitAsync(cancellationToken).ConfigureAwait(false);
return new SemaphoreDisposer(semaphore);
}

public struct SemaphoreDisposer : IDisposable
{
private readonly SemaphoreSlim _semaphore;

public SemaphoreDisposer(SemaphoreSlim semaphore)
{
_semaphore = semaphore;
}

public void Dispose()
{
_semaphore.Release();
}
}
}
}

0 comments on commit 4f1cf9b

Please sign in to comment.