-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathInMemoryCache.cs
69 lines (59 loc) · 1.68 KB
/
InMemoryCache.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
public class InMemoryCache<T> : ICache, IDisposable
{
public const int DEFAULT_MEMORY_EXPIRATION_TIME_IN_SECONDS = 2 * 60;
private IMemoryCache _memoryCache;
private int AbsoluteCacheExpiryTimeInSeconds { get; }
private static object _padlock = new object();
public static InMemoryCache<T> Instance
{
get
{
if (_instance == null)
{
lock (_padlock)
{
if (_instance == null)
{
_instance = new InMemoryCache<T>(DEFAULT_MEMORY_EXPIRATION_TIME_IN_SECONDS);
}
}
}
return _instance;
}
}
private static InMemoryCache<T> _instance;
protected InMemoryCache(int absoluteExpiryTimeInSeconds)
{
MemoryCacheOptions memoryCacheOptions = new MemoryCacheOptions();
memoryCacheOptions.ExpirationScanFrequency = TimeSpan.FromMinutes(3);
_memoryCache = new MemoryCache(memoryCacheOptions);
AbsoluteCacheExpiryTimeInSeconds = absoluteExpiryTimeInSeconds;
}
public T Get(string key)
{
T cacheItem = default(T);
lock (_padlock)
{
_memoryCache.TryGetValue(key, out cacheItem);
}
return cacheItem;
}
public void Put(string key, T item)
{
lock (_padlock)
{
_memoryCache.Set(key, item, TimeSpan.FromSeconds(AbsoluteCacheExpiryTimeInSeconds));
}
}
public void Remove(string key)
{
lock (_padlock)
{
_memoryCache.Remove(key);
}
}
public void Dispose()
{
_memoryCache.Dispose();
}
}