Class LruCache<TKey, TValue>
a size-limited cache of key value pairs
Once the maximum size has been reached, the least recently used pairs will be evicted to make room for any new items.
public class LruCache<TKey, TValue> where TKey : class where TValue : class
Type Parameters
TKey
TValue
- Inheritance
-
LruCache<TKey, TValue>
- Inherited Members
Constructors
LruCache(int)
Construct a new LruCache.
public LruCache(int maxEntries)
Parameters
maxEntries
intmaximum number of entries before items are evicted
Properties
Count
the number of items in the cache
public int Count { get; }
Property Value
MaxEntries
the maximum number of entries this LruCache will hold before items begin getting evicted
public int MaxEntries { get; }
Property Value
Methods
AddOrUpdate(TKey, TValue)
Add the key/value pair to the cache, or update the value if the key already exists.
If the cache is full, evicts the least recently used item.
public void AddOrUpdate(TKey key, TValue value)
Parameters
key
TKeyvalue
TValue
Clear()
Clear the LruCache of all entries.
public void Clear()
Evict(TKey)
Evicts a specific key out of the cache if it exists
public void Evict(TKey key)
Parameters
key
TKeythe key to evict from the cache
EvictExpiredLRUListItems(int)
Method to evict expired LRUListItems.
public void EvictExpiredLRUListItems(int validityInSeconds)
Parameters
validityInSeconds
intNumber of seconds the LRUListItems are valid for.
FindOldestItem()
Returns the least recently used item if it exists.
public LruListItem<TKey, TValue> FindOldestItem()
Returns
- LruListItem<TKey, TValue>
The item that is least recently used or the default value of the LruListItem class if the LRU cache is empty.
GetOrAdd(TKey, Func<TKey, TValue>)
Try to get the value associated with the key, if it doesn't exist, use the provided factory method to create a new value and tries adding it to the cache.
public TValue GetOrAdd(TKey key, Func<TKey, TValue> factory)
Parameters
key
TKeythe key to look up
factory
Func<TKey, TValue>the factory method used in case the key is not present in the cache
Returns
- TValue
the looked up value or the value created by the factory
TryGetValue(TKey, out TValue)
Try to get the value associated with the key.
public bool TryGetValue(TKey key, out TValue value)
Parameters
key
TKeythe key to look up
value
TValuethe value, if the key exists
Returns
- bool
true if there is a value associated with the key, or false if no value is associated with the key