-
Notifications
You must be signed in to change notification settings - Fork 0
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Added SemaphoreSlim extension methods
- Loading branch information
Showing
1 changed file
with
50 additions
and
0 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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(); | ||
} | ||
} | ||
} | ||
} |