-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathMemoryCache.cs
More file actions
79 lines (61 loc) · 2.03 KB
/
Copy pathMemoryCache.cs
File metadata and controls
79 lines (61 loc) · 2.03 KB
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
namespace Graphnode.BlazorIconify.SourceGenerator;
using System;
using System.Collections.Concurrent;
/// <summary>
/// A simple in-memory cache implementation for source generators
/// </summary>
public class MemoryCache
{
private readonly ConcurrentDictionary<string, CacheEntry> _cache = new();
public T? Get<T>(string key)
{
if (!_cache.TryGetValue(key, out var entry))
return default;
if (IsExpired(entry))
{
// Remove expired item
_cache.TryRemove(key, out _);
return default;
}
return (T?)entry.Value;
}
public bool TryGetValue<T>(string key, out T? value)
{
if (key is null)
throw new ArgumentNullException(nameof(key));
value = default;
if (!_cache.TryGetValue(key, out var entry))
return false;
if (IsExpired(entry))
{
// Remove expired item
_cache.TryRemove(key, out _);
return false;
}
value = (T?)entry.Value;
return true;
}
public void Set<T>(string key, T? value, TimeSpan? absoluteExpiration = null)
{
if (key is null)
throw new ArgumentNullException(nameof(key));
var expirationTime = absoluteExpiration.HasValue
? DateTimeOffset.UtcNow.Add(absoluteExpiration.Value)
: DateTimeOffset.MaxValue;
var entry = new CacheEntry(value, expirationTime);
_cache.AddOrUpdate(key, entry, (_, _) => entry);
}
public bool Remove(string key)
{
if (key is null)
throw new ArgumentNullException(nameof(key));
return _cache.TryRemove(key, out _);
}
public void Clear() => _cache.Clear();
private static bool IsExpired(CacheEntry entry) => entry.ExpirationTime <= DateTimeOffset.UtcNow;
private class CacheEntry(object? value, DateTimeOffset expirationTime)
{
public object? Value { get; } = value;
public DateTimeOffset ExpirationTime { get; } = expirationTime;
}
}