-
Notifications
You must be signed in to change notification settings - Fork 37
ConcurrentTLru
Alex Peck edited this page May 19, 2022
·
18 revisions
ConcurrentTLru is a thread-safe bounded size pseudo TLRU. It's exactly like ConcurrentLru, but items have TTL. This page describes how to use the ConcurrentTLru.
ConcurrentTLru is intended to be a drop in replacement for ConcurrentDictionary, but with the benefit of bounded size based on a TLRU eviction policy.
The code samples below illustrate how to create an LRU then get/remove/update items:
int capacity = 666;
TimeSpan ttl = TimeSpan.FromMinutes(5);
var lru = new ConcurrentTLru<int, SomeItem>(capacity, ttl);
bool success1 = lru.TryGet(1, out var value);
var value1 = lru.GetOrAdd(1, (k) => new SomeItem(k));
var value2 = await lru.GetOrAddAsync(0, (k) => Task.FromResult(new SomeItem(k)));
bool success2 = lru.TryRemove(1);
lru.Clear();
var item = new SomeItem(1);
bool success3 = lru.TryUpdate(1, item);
lru.AddOrUpdate(1, item);
Console.WriteLine(lru.HitRatio);
// enumerate keys
foreach (var k in lru.Keys)
{
Console.WriteLine(k);
}
// enumerate key value pairs
foreach (var kvp in lru)
{
Console.WriteLine($"{kvp.Key} {kvp.Value}");
}
// register event on item removed
lru.ItemRemoved += (source, eventArgs) => Console.WriteLine($"{eventArgs.Reason} {eventArgs.Key} {eventArgs.Value}");