Concurrent Cache
ConcurrentCache<TKey,TValue> is a thread-safe cache that provides API similar to ConcurrentDictionary<TKey,TValue>. It supports LRU and LFU eviction policies. The cache is limited only by size in contrast to System.Runtime.Caching.MemoryCache or Microsoft.Extensions.Caching.Memory.MemoryCache.
Note
Time-based eviction policy is not supported.
The following example demonstrates how to create the cache:
using DotNext.Runtime.Caching;
var cache = new ConcurrentCache<int, string>(100, CacheEvictionPolicy.LRU)
{
Eviction = static (int key, string value) => Console.WriteLine($"Evicted entry: key = {key}, value = {value}"),
};
cache.TryAdd(42, "Hello, world!");
cache.TryGetValue(42, out string result);
ConcurrentCache<TKey, TValue>.Count
property has O(1) time complexity. The cache supports asynchronous invocation that allows to remove cleanup activites from cache consumption thread. This feature is disabled by default. Set ExecuteEvictionAsynchronously
property to true to enable asynchronous eviction:
var cache = new ConcurrentCache<int, string>(100, CacheEvictionPolicy.LRU)
{
Eviction = static (int key, string value) => Console.WriteLine($"Evicted entry: key = {key}, value = {value}"),
ExecuteEvictionAsynchronously = true,
};