-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathAsynchronousLock.cs
More file actions
60 lines (50 loc) · 1.63 KB
/
AsynchronousLock.cs
File metadata and controls
60 lines (50 loc) · 1.63 KB
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
using System.Threading.Tasks;
#pragma warning disable IDE0130 // 命名空间与文件夹结构不匹配
namespace System.Threading
#pragma warning restore IDE0130 // 命名空间与文件夹结构不匹配
{
/// <summary>
/// 异步锁 (悲观锁)。
/// </summary>
public sealed class AsynchronousLock : IDisposable
{
private readonly SemaphoreSlim _semaphore;
private readonly IDisposable _releaser;
/// <summary>
/// 构造函数。
/// </summary>
public AsynchronousLock()
{
_semaphore = new SemaphoreSlim(1, 1);
_releaser = new Releaser(_semaphore);
}
/// <summary>
/// 请求锁。
/// </summary>
/// <returns></returns>
public IDisposable Acquire()
{
_semaphore.Wait();
return _releaser;
}
/// <summary>
/// 请求锁。
/// </summary>
/// <param name="cancellationToken">取消。</param>
/// <returns></returns>
public async Task<IDisposable> AcquireAsync(CancellationToken cancellationToken = default)
{
await _semaphore.WaitAsync(cancellationToken)
.ConfigureAwait(false);
return _releaser;
}
private sealed class Releaser : IDisposable
{
private readonly SemaphoreSlim _semaphore;
public Releaser(SemaphoreSlim semaphore) => _semaphore = semaphore;
public void Dispose() => _semaphore.Release();
}
/// <inheritdoc />
public void Dispose() => _semaphore.Dispose();
}
}