-
Notifications
You must be signed in to change notification settings - Fork 337
Expand file tree
/
Copy pathDistributedLock.cs
More file actions
187 lines (149 loc) · 5.64 KB
/
DistributedLock.cs
File metadata and controls
187 lines (149 loc) · 5.64 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
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
using Microsoft.Extensions.Logging;
using System;
using System.Diagnostics;
using System.Threading;
using System.Threading.Tasks;
namespace EasyCaching.Core.DistributedLock
{
public class DistributedLock : MemoryLock
{
private readonly IDistributedLockProvider _provider;
private readonly Lock _syncObj = LockFactory.Create();
private readonly DistributedLockOptions _options;
private readonly ILogger _logger;
private byte[] _value;
private Timer _timer;
public DistributedLock(string name, string key, IDistributedLockProvider provider, DistributedLockOptions options, ILoggerFactory loggerFactory = null) : base($"{name}/{key}")
{
_provider = provider;
_options = options;
_logger = loggerFactory?.CreateLogger(GetType().FullName);
}
public override bool Lock(int millisecondsTimeout, CancellationToken cancellationToken)
{
var sw = Stopwatch.StartNew();
if (base.Lock(millisecondsTimeout, cancellationToken))
{
GetNewGuid();
do
{
try
{
if (_provider.Add(Key, _value, _options.MaxTtl))
{
StartPing();
return true;
}
}
catch (Exception ex)
{
_logger?.LogWarning(default, ex, ex.Message);
if (!_provider.CanRetry(ex)) break;
}
if (cancellationToken.IsCancellationRequested)
{
_value = null;
cancellationToken.ThrowIfCancellationRequested();
}
Thread.Sleep(Math.Max(0, Math.Min(100, millisecondsTimeout - (int)sw.ElapsedMilliseconds)));
} while (sw.ElapsedMilliseconds < millisecondsTimeout);
_logger?.LogWarning($"{Key}/Wait fail");
base.Release();
}
_value = null;
return false;
}
public override async ValueTask<bool> LockAsync(int millisecondsTimeout, CancellationToken cancellationToken)
{
var sw = Stopwatch.StartNew();
if (await base.LockAsync(millisecondsTimeout, cancellationToken))
{
GetNewGuid();
do
{
try
{
if (await _provider.AddAsync(Key, _value, _options.MaxTtl))
{
StartPing();
return true;
}
}
catch (Exception ex)
{
_logger?.LogWarning(default, ex, ex.Message);
if (!_provider.CanRetry(ex)) break;
}
if (cancellationToken.IsCancellationRequested)
{
_value = null;
cancellationToken.ThrowIfCancellationRequested();
}
await Task.Delay(Math.Max(0, Math.Min(100, millisecondsTimeout - (int)sw.ElapsedMilliseconds)), cancellationToken);
} while (sw.ElapsedMilliseconds < millisecondsTimeout);
_logger?.LogWarning($"{Key}/Wait fail");
await base.ReleaseAsync();
}
_value = null;
return false;
}
public override void Release()
{
Interlocked.Exchange(ref _timer, null)?.Dispose();
var value = Interlocked.Exchange(ref _value, null);
if (value == null) return;
try
{
if (_provider.Delete(Key, value)) _logger?.LogInformation($"{Key}/Release lock");
else _logger?.LogWarning($"{Key}/Release lock fail");
}
finally
{
base.Release();
}
}
public override async ValueTask ReleaseAsync()
{
Interlocked.Exchange(ref _timer, null)?.Dispose();
var value = Interlocked.Exchange(ref _value, null);
if (value == null) return;
try
{
if (await _provider.DeleteAsync(Key, value)) _logger?.LogInformation($"{Key}/Release lock");
else _logger?.LogWarning($"{Key}/Release lock fail");
}
finally
{
await base.ReleaseAsync();
}
}
private void GetNewGuid()
{
lock (_syncObj)
{
if (_value != null) throw new DistributedLockException();
var id = Guid.NewGuid();
_value = id.ToByteArray();
_logger?.LogDebug($"{Key}/NewGuid: {id:D}");
}
}
private void StartPing()
{
_logger?.LogInformation($"{Key}/Wait success, start ping");
_timer = new Timer(Ping, this, _options.DueTime, _options.Period);
}
private static async void Ping(object state)
{
var self = (DistributedLock)state;
try
{
await self._provider.SetAsync(self.Key, self._value, self._options.MaxTtl);
self._logger?.LogDebug($"{self.Key}/Ping success");
}
catch (Exception ex)
{
self._logger?.LogWarning(default, ex, $"{self.Key}/Ping fail");
}
}
}
}