-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathSimpleLock.cs
44 lines (34 loc) · 1.41 KB
/
SimpleLock.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
using System;
using System.Collections.Concurrent;
using System.Threading;
using Composite;
namespace Hangfire.CompositeC1
{
public class SimpleLock : IDisposable
{
private static readonly ConcurrentDictionary<string, object> Locks = new ConcurrentDictionary<string, object>();
private readonly object _lock;
private SimpleLock(string resource, TimeSpan timeout)
{
Verify.ArgumentNotNullOrEmpty(resource, "resource");
if (timeout.TotalSeconds > int.MaxValue)
{
throw new ArgumentException($"The timeout specified is too large. Please supply a timeout equal to or less than {int.MaxValue} seconds", nameof(timeout));
}
if (timeout.TotalMilliseconds > int.MaxValue)
{
throw new ArgumentException($"The timeout specified is too large. Please supply a timeout equal to or less than {(int)TimeSpan.FromMilliseconds(int.MaxValue).TotalSeconds} seconds", nameof(timeout));
}
_lock = Locks.GetOrAdd(resource, s => new object());
Monitor.TryEnter(_lock, timeout);
}
public static IDisposable AcquireLock(string resource, TimeSpan timeout)
{
return new SimpleLock(resource, timeout);
}
public void Dispose()
{
Monitor.Exit(_lock);
}
}
}