Created
July 13, 2023 02:28
-
-
Save crozone/19ceafc4bf2706e77423a54af6d8a5ac to your computer and use it in GitHub Desktop.
C# AsyncLock based on SemaphoreSlim
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 class AsyncLock | |
{ | |
private readonly SemaphoreSlim semaphore = new SemaphoreSlim(1, 1); | |
private readonly Task<IDisposable> releaser; | |
public AsyncLock() | |
{ | |
releaser = Task.FromResult((IDisposable)new AsyncLockReleaser(this)); | |
} | |
public Task<IDisposable> LockAsync(CancellationToken cancellationToken) | |
{ | |
Task wait = semaphore.WaitAsync(cancellationToken); | |
return wait.IsCompleted ? | |
releaser : | |
wait.ContinueWith( | |
(_, state) => (IDisposable)state!, | |
releaser.Result, | |
CancellationToken.None, | |
TaskContinuationOptions.ExecuteSynchronously, | |
TaskScheduler.Default); | |
} | |
private sealed class AsyncLockReleaser : IDisposable | |
{ | |
private readonly AsyncLock toRelease; | |
internal AsyncLockReleaser(AsyncLock toRelease) { | |
this.toRelease = toRelease; | |
} | |
public void Dispose() | |
{ | |
toRelease.semaphore.Release(); | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment