-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathLockProvider.cs
64 lines (50 loc) · 1.75 KB
/
LockProvider.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
using System;
using System.Threading.Tasks;
using MongoDB.Driver;
namespace mongodb_locks
{
public interface ILockProvider
{
Task<IDisposable> AcquireLock(string resourceId);
}
public class LockProvider : ILockProvider
{
private readonly IMongoCollection<LockModel> collection;
public LockProvider(string mongodbConnString)
{
// Create a lock collection
var client = new MongoClient(mongodbConnString);
var database = client.GetDatabase("mydb");
// Get our collection
collection = database.GetCollection<LockModel>("resourceLocks");
// Specify a TTL index on the ExpiryPoint field.
collection.Indexes.CreateOne(new CreateIndexModel<LockModel>(
Builders<LockModel>.IndexKeys.Ascending(l => l.ExpireAt),
new CreateIndexOptions
{
ExpireAfter = TimeSpan.Zero
}
));
}
public async Task<IDisposable> AcquireLock(string resourceId)
{
// Determine the id of the lock
var lockId = $"lock_{resourceId}";
var distributedLock = new DistributedLock(collection, lockId);
var startLockAcquireTime = DateTime.Now;
// Try and acquire the lock
while (!await distributedLock.AttemptGetLock())
{
// If we failed to acquire the lock, wait a moment.
await Task.Delay(100);
// Only try to acquire the lock for 10 seconds
if ((DateTime.Now - startLockAcquireTime).TotalSeconds > 10)
{
throw new ApplicationException($"Could not acquire lock for {resourceId} within the timeout.");
}
}
// This will only return if we have the lock.
return distributedLock;
}
}
}