Repository navigation
Expand file tree
/
Copy pathInMemoryDistributedLock.cs
More file actions
82 lines (66 loc) · 2.7 KB
/
Copy pathInMemoryDistributedLock.cs
File metadata and controls
82 lines (66 loc) · 2.7 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
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
using Medallion.Threading;
namespace MagicCSharp.Testing;
/// <inheritdoc cref="InMemoryDistributedLockProvider" />
public class InMemoryDistributedLock(string name, InMemoryDistributedLockProvider provider) : IDistributedLock
{
public string Name { get; } = name;
private SemaphoreSlim Semaphore => provider.GetOrCreateSemaphore(Name);
public IDistributedSynchronizationHandle Acquire(TimeSpan? timeout = null, CancellationToken cancellationToken = default)
{
if (ShouldReenter())
{
return new ReentrantHandle();
}
var waitTimeout = timeout ?? Timeout.InfiniteTimeSpan;
if (!Semaphore.Wait(waitTimeout, cancellationToken))
{
throw new TimeoutException($"Failed to acquire in-memory distributed lock '{Name}' within {waitTimeout}.");
}
provider.MarkHeld(Name);
return new InMemoryDistributedSynchronizationHandle(Semaphore, provider, Name);
}
public async ValueTask<IDistributedSynchronizationHandle> AcquireAsync(TimeSpan? timeout = null, CancellationToken cancellationToken = default)
{
if (ShouldReenter())
{
return new ReentrantHandle();
}
var waitTimeout = timeout ?? Timeout.InfiniteTimeSpan;
if (!await Semaphore.WaitAsync(waitTimeout, cancellationToken).ConfigureAwait(false))
{
throw new TimeoutException($"Failed to acquire in-memory distributed lock '{Name}' within {waitTimeout}.");
}
provider.MarkHeld(Name);
return new InMemoryDistributedSynchronizationHandle(Semaphore, provider, Name);
}
public IDistributedSynchronizationHandle? TryAcquire(TimeSpan timeout = default, CancellationToken cancellationToken = default)
{
if (ShouldReenter())
{
return new ReentrantHandle();
}
if (!Semaphore.Wait(timeout, cancellationToken))
{
return null;
}
provider.MarkHeld(Name);
return new InMemoryDistributedSynchronizationHandle(Semaphore, provider, Name);
}
public async ValueTask<IDistributedSynchronizationHandle?> TryAcquireAsync(TimeSpan timeout = default, CancellationToken cancellationToken = default)
{
if (ShouldReenter())
{
return new ReentrantHandle();
}
if (!await Semaphore.WaitAsync(timeout, cancellationToken).ConfigureAwait(false))
{
return null;
}
provider.MarkHeld(Name);
return new InMemoryDistributedSynchronizationHandle(Semaphore, provider, Name);
}
private bool ShouldReenter()
{
return InMemoryDistributedLockProvider.ReentrancyDepth.Value > 0 && provider.IsHeld(Name);
}
}