/
AsyncLock.cs
83 lines (71 loc) · 2.44 KB
/
AsyncLock.cs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
// Copyright (c) Six Labors.
// Licensed under the Six Labors Split License.
namespace SixLabors.ImageSharp.Web.Synchronization;
/// <summary>
/// An asynchronous locker that uses an IDisposable pattern for releasing the lock.
/// </summary>
public sealed class AsyncLock : IDisposable
{
private readonly SemaphoreSlim semaphore;
private readonly IDisposable releaser;
private readonly Task<IDisposable> releaserTask;
/// <summary>
/// Initializes a new instance of the <see cref="AsyncLock"/> class.
/// </summary>
public AsyncLock()
{
this.semaphore = new SemaphoreSlim(1, 1);
this.releaser = new Releaser(this);
this.releaserTask = Task.FromResult(this.releaser);
}
/// <summary>
/// Gets or sets the callback that should be invoked whenever this lock is released.
/// </summary>
public Action? OnRelease { get; set; }
/// <summary>
/// Asynchronously obtains the lock. Dispose the returned <see cref="IDisposable"/> to release the lock.
/// </summary>
/// <returns>
/// The <see cref="IDisposable"/> that will release the lock.
/// </returns>
public Task<IDisposable> LockAsync()
{
Task wait = this.semaphore.WaitAsync();
// No-allocation fast path when the semaphore wait completed synchronously
return (wait.Status == TaskStatus.RanToCompletion)
? this.releaserTask
: AwaitThenReturn(wait, this.releaser);
static async Task<IDisposable> AwaitThenReturn(Task t, IDisposable r)
{
await t;
return r;
}
}
private void Release()
{
try
{
this.semaphore.Release();
}
finally
{
this.OnRelease?.Invoke();
}
}
/// <summary>
/// Releases all resources used by the current instance of the <see cref="AsyncLock"/> class.
/// </summary>
public void Dispose() => this.semaphore.Dispose();
/// <summary>
/// Utility class that releases an <see cref="AsyncLock"/> on disposal.
/// </summary>
private sealed class Releaser : IDisposable
{
private readonly AsyncLock toRelease;
internal Releaser(AsyncLock toRelease) => this.toRelease = toRelease;
/// <summary>
/// Releases the <see cref="AsyncLock"/> associated with this <see cref="Releaser"/>.
/// </summary>
public void Dispose() => this.toRelease?.Release();
}
}