Skip to content

SlidingCache2 Class` ​

Definition ​

Thread-safe, bounded, in-memory cache with sliding expiration and approximate Least Recently Used (LRU) eviction.

  • Namespace: JASE.Caching
  • Assembly: JASE.Caching.dll

Constructors ​

NameDescription
`SlidingCache`2(TimeSpan slidingTtl, int maxEntries)`Initializes a new SlidingCache`2 with a sliding expiration and a fixed maximum size.
`SlidingCache`2(TimeSpan slidingTtl, int maxEntries, int trimEveryNAdds)`Initializes a new cache instance.
`SlidingCache`2(TimeSpan slidingTtl, int maxEntries, int trimEveryNAdds, TimeSpan minPruneInterval)`Initializes a new cache instance with an explicit minimum prune interval.
`SlidingCache`2(TimeSpan slidingTtl, int maxEntries, int trimEveryNAdds, TimeSpan? minPruneInterval, Func<TKey, TValue, SlidingCacheEvictionReason, bool> evictCallback)`Initializes a new cache instance with optional pruning and eviction callback configuration.

Properties ​

NameDescription
CountGets the current number of entries in the cache.
MinimalPruneIntervalDefaultGets the default minimum interval between time-based prune runs.

Methods ​

NameDescription
void Clear()Removes all entries from the cache.
TValue GetOrAdd(TKey key, Func<TKey, TValue> factory)Gets the value for the specified key, or adds a new value created by factory if absent.
void Set(TKey key, TValue value)Adds or replaces the value associated with the specified key.
void Trim()Forces an immediate prune pass.
bool TryGetValue(TKey key, out TValue value)Attempts to get the value associated with the specified key.
bool TryRemove(TKey key)Attempts to remove the value associated with the specified key.

Remarks ​

Each entry is associated with a sliding time-to-live (TTL). Successful reads refresh the entry’s last-access timestamp. Entries are evicted when they expire, when the cache exceeds the configured maximum size, or when explicitly removed/replaced.

Recency is tracked via internal queues to approximate LRU behavior without global locks. Pruning is executed opportunistically during reads and adds, and may lag slightly behind real-time expiration under heavy contention.

Timing is based on a monotonic tick source, using Environment.TickCount64 in the default system clock.

Disposal: If TValue implements IDisposable, values are disposed when evicted unless the eviction callback claims ownership.