Skip to content

Instantly share code, notes, and snippets.

@alexperovich
Last active September 24, 2019 23:28
Show Gist options
  • Save alexperovich/5c02d704966f3c35f94a0ddee25cc115 to your computer and use it in GitHub Desktop.
Save alexperovich/5c02d704966f3c35f94a0ddee25cc115 to your computer and use it in GitHub Desktop.
public struct SemaphoreLock : IDisposable
{
private readonly SemaphoreSlim sem;
private SemaphoreLock(SemaphoreSlim sem)
{
this.sem = sem;
}
public void Dispose()
{
sem.Release();
}
public static ValueTask<SemaphoreLock> LockAsync(SemaphoreSlim sem)
{
var waitTask = sem.WaitAsync();
if (waitTask.IsCompletedSuccessfully)
{
return new ValueTask<SemaphoreLock>(new SemaphoreLock(sem));
}
static async Task<SemaphoreLock> WaitForLock(Task waitTask, SemaphoreSlim sem)
{
await waitTask.ConfigureAwait(false);
return new SemaphoreLock(sem);
}
return new ValueTask<SemaphoreLock>(WaitForLock(waitTask, sem));
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment