Skip to content

ConcurrentLfu Quickstart

Alex Peck edited this page Sep 12, 2022 · 8 revisions

ConcurrentLfu is a thread-safe bounded size approximate LFU.

Constructor

int capacity = 666;
var lfu = new ConcurrentLfu<int, SomeItem>(capacity);

Getting Items

bool success1 = lfu.TryGet(1, out var value);
var value1 = lfu.GetOrAdd(1, (k) => new SomeItem(k));
var value2 = await lfu.GetOrAddAsync(0, (k) => Task.FromResult(new SomeItem(k)));

Removing Items

bool success2 = lfu.TryRemove(1); // remove item with key == 1
lfu.Clear();
lfu.Eviction.Policy.Value.Trim(1); // remove the least recently used item

Updating Items

var item = new SomeItem(1);
bool success3 = lfu.TryUpdate(1, item);
lfu.AddOrUpdate(1, item);

Diagnostics

Console.WriteLine(lfu.Metrics.Value.HitRatio);

// enumerate keys
foreach (var k in lfu.Keys)
{
   Console.WriteLine(k);
}

// enumerate key value pairs
foreach (var kvp in lfu)
{
   Console.WriteLine($"{kvp.Key} {kvp.Value}");
}