-
Notifications
You must be signed in to change notification settings - Fork 7
/
Copy pathCache.linq
38 lines (34 loc) · 976 Bytes
/
Cache.linq
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
public class Cache<TKey, TValue> where TKey : struct
{
private readonly Dictionary<TKey, CacheItem<TValue>> _cache = new();
public void Store(TKey key, TValue value, TimeSpan expiresAfter)
{
_cache[key] = new CacheItem<TValue>(value, expiresAfter);
}
public void Store(TKey key, TValue value, int expiresAfterInSeconds)
{
_cache[key] = new CacheItem<TValue>(value, TimeSpan.FromSeconds(expiresAfterInSeconds));
}
public TValue Get(TKey key)
{
if (!_cache.ContainsKey(key)) return default(TValue)!;
var cached = _cache[key];
if (DateTimeOffset.UtcNow.Subtract(cached.Created) >= cached.ExpiresAfter)
{
_cache.Remove(key);
return default(TValue)!;
}
return cached.Value;
}
}
public class CacheItem<T>
{
public CacheItem(T value, TimeSpan expiresAfter)
{
Value = value;
ExpiresAfter = expiresAfter;
}
public T Value { get; }
internal DateTimeOffset Created { get; } = DateTimeOffset.UtcNow;
internal TimeSpan ExpiresAfter { get; }
}