c#
public sealed class UaDetectorMemoryCache<T>
{
private readonly UaDetectorCacheOptions _cacheOptions;
private readonly ConcurrentDictionary<string, LinkedListNode<T>> _cache = new();
private readonly LinkedList<T> _lruList = [];
private readonly object _lock = new();
public UaDetectorMemoryCache(UaDetectorCacheOptions cacheOptions)
{
_cacheOptions = cacheOptions;
}
public bool TryGet(string key, [NotNullWhen(true)] out T? result)
{
if (_cache.TryGetValue(key, out var node))
{
_lruList.Remove(node);
_lruList.AddFirst(node);
result = node.Value;
}
else
{
result = default;
}
return result is not null;
}
public void Put(string key, T value)
{
if (_cache.TryGetValue(key, out var node))
{
_lruList.Remove(node);
_lruList.AddFirst(node);
}
else
{
node = new LinkedListNode<T>(value);
if (_cache.Count == _cacheOptions.Capacity)
{
_lruList.RemoveLast();
}
_lruList.AddFirst(node);
_cache.TryAdd(key, node);
}
}
}
c#
public sealed class UaDetectorMemoryCache<T>
{
private readonly UaDetectorCacheOptions _cacheOptions;
private readonly ConcurrentDictionary<string, LinkedListNode<T>> _cache = new();
private readonly LinkedList<T> _lruList = [];
private readonly object _lock = new();
public UaDetectorMemoryCache(UaDetectorCacheOptions cacheOptions)
{
_cacheOptions = cacheOptions;
}
public bool TryGet(string key, [NotNullWhen(true)] out T? result)
{
if (_cache.TryGetValue(key, out var node))
{
_lruList.Remove(node);
_lruList.AddFirst(node);
result = node.Value;
}
else
{
result = default;
}
return result is not null;
}
public void Put(string key, T value)
{
if (_cache.TryGetValue(key, out var node))
{
_lruList.Remove(node);
_lruList.AddFirst(node);
}
else
{
node = new LinkedListNode<T>(value);
if (_cache.Count == _cacheOptions.Capacity)
{
_lruList.RemoveLast();
}
_lruList.AddFirst(node);
_cache.TryAdd(key, node);
}
}
}