-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathMemoryCacheBase.cs
94 lines (85 loc) · 2.66 KB
/
MemoryCacheBase.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
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
using System;
using System.Threading;
using System.Threading.Tasks;
namespace TorExitNodeManager
{
internal abstract class MemoryCacheBase<T> where T : new()
{
private readonly ManualResetEventSlim _hasDataLock = new ManualResetEventSlim(false);
private readonly AutoResetEvent _populatingLock = new AutoResetEvent(true);
private readonly ReaderWriterLockSlim _updateLock = new ReaderWriterLockSlim(LockRecursionPolicy.NoRecursion);
private T _cache;
private DateTime _cacheLastUpdated = DateTime.MinValue;
protected TimeSpan _ttl = TimeSpan.FromMinutes(new Random().Next(5, 10));
public T Data
{
get
{
CheckIfPopulated();
try
{
if (_updateLock.TryEnterReadLock(2500))
return _cache;
}
finally
{
_updateLock.ExitReadLock();
}
return new T();
}
}
public void Invalidate()
{
PopulateCache(true);
}
protected abstract T FetchCacheData();
private void CheckIfPopulated()
{
if (DateTime.UtcNow.Subtract(_cacheLastUpdated) > _ttl)
{
Task.Factory.StartNew(PopulateCache);
_hasDataLock.Wait(2500);
}
}
private void PopulateCache()
{
PopulateCache(false);
}
private void PopulateCache(bool force)
{
if (_populatingLock.WaitOne(1))
{
try
{
if (force || DateTime.UtcNow.Subtract(_cacheLastUpdated) > _ttl)
{
T newCache = FetchCacheData();
if (_updateLock.TryEnterWriteLock(10000))
{
try
{
_cache = newCache;
_cacheLastUpdated = DateTime.UtcNow;
}
catch
{
}
finally
{
_updateLock.ExitWriteLock();
_hasDataLock.Set();
}
}
}
}
catch
{
}
finally
{
_populatingLock.Set();
}
}
}
}
}