Last active
September 24, 2019 23:28
-
-
Save alexperovich/5c02d704966f3c35f94a0ddee25cc115 to your computer and use it in GitHub Desktop.
This file contains hidden or 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
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