Neuron®
The Neuron® is the basis for the creation of open and secure federated networks for smart societies.
Loading...
Searching...
No Matches
AsyncLock.cs
1using System;
2using System.Threading;
3using System.Threading.Tasks;
4
6{
10 public sealed class AsyncLock : IDisposable, IAsyncDisposable
11 {
12 private readonly SemaphoreSlim semaphore = new(1, 1);
13 private bool disposed;
14
19 public async ValueTask<Releaser> LockAsync(CancellationToken cancellationToken = default)
20 {
21 await this.semaphore.WaitAsync(cancellationToken).ConfigureAwait(false);
22 return new Releaser(this);
23 }
24
28 public sealed class Releaser : IDisposable, IAsyncDisposable
29 {
30 private AsyncLock? owner;
31 internal Releaser(AsyncLock owner) { this.owner = owner; }
32 public void Dispose()
33 {
34 AsyncLock? O = Interlocked.Exchange(ref this.owner, null);
35 if (O is not null && !O.disposed)
36 {
37 O.semaphore.Release();
38 }
39 }
40 public ValueTask DisposeAsync()
41 {
42 this.Dispose();
43 return ValueTask.CompletedTask;
44 }
45 }
46
47 public void Dispose()
48 {
49 if (this.disposed) return;
50 this.disposed = true;
51 this.semaphore.Dispose();
52 }
53
54 public ValueTask DisposeAsync()
55 {
56 this.Dispose();
57 return ValueTask.CompletedTask;
58 }
59 }
60}
Disposable releaser. Class (not struct) to avoid double-release via accidental copies.
Definition: AsyncLock.cs:29
Simple async-exclusive lock (lightweight). Each call to LockAsync yields a disposable releaser that m...
Definition: AsyncLock.cs:11
async ValueTask< Releaser > LockAsync(CancellationToken cancellationToken=default)
Acquires the lock asynchronously, returning a disposable releaser that must be disposed exactly once.
Definition: AsyncLock.cs:19