Skip to content

SlidingCache<TKey, TValue> ​

Thread-safe, bounded, in-memory cache with sliding expiration and approximate LRU eviction.

  • Storage: ConcurrentDictionary<TKey, Entry>
  • Recency tracking: lock-free queues (ConcurrentQueue<TKey>) to approximate LRU without global locks
  • Time source: Environment.TickCount64 (monotonic-ish milliseconds; not wall clock)
  • Pruning: opportunistic during reads and adds; may lag under heavy contention

TKey must be non-nullable (where TKey : notnull).

Core semantics ​

Sliding expiration ​

Each entry has a sliding TTL (slidingTtl). A successful read:

  • validates expiration (now - lastAccess < ttl)
  • updates the last-access tick (Touch(now)), refreshing TTL

If an entry is found but expired, it is removed and treated as a miss.

Bounded size + approximate LRU eviction ​

The cache has a strict maxEntries target. When exceeded (or when Trim() is forced), the cache evicts entries using an approximate LRU mechanism:

  • keys are tracked in _touchQueue when first inserted and after reads
  • eviction iterates that queue and removes entries that are “old-ish”
  • “old-ish” is defined as: now - lastAccess > minAgeToEvictMs
    • where minAgeToEvictMs = ttlMs / 2 (at least 1ms)

This avoids evicting hot items simply because they appear in the queue.


Pruning model ​

Pruning work is triggered in two ways:

1) Size pressure ​

Prune triggers whenever _map.Count > maxEntries.

2) Time-based pruning (rate-limited) ​

When enabled, pruning is rate-limited by minPruneInterval:

  • each prune window is claimed using Interlocked.CompareExchange on _nextPruneTick
  • only one thread wins a given time window
  • use TimeSpan.Zero to disable time-based pruning (size-based pruning still occurs)

Opportunistic execution ​

Pruning is not on a dedicated timer. It is invoked opportunistically:

  • TryGetValue(...) calls _pruneGate.OnRead()
  • GetOrAdd(...) and Set(...) call _pruneGate.OnAdd()

Reads prune less frequently than adds:

  • adds trigger every trimEveryNAdds
  • reads trigger every trimEveryNAdds * 4

Constructors ​

Basic ​

csharp
var cache = new SlidingCache<TKey, TValue>(slidingTtl, maxEntries);

Defaults:

  • trimEveryNAdds = 256
  • minPruneInterval = MinimalPruneIntervalDefault (1 minute)
  • no eviction callback

Custom Cadence ​

csharp
var cache = new SlidingCache<TKey, TValue>(slidingTtl, maxEntries, trimEveryNAdds);

Custom prune interval ​

csharp
var cache = new SlidingCache<TKey, TValue>(
    slidingTtl,
    maxEntries,
    trimEveryNAdds,
    minPruneInterval: TimeSpan.FromSeconds(30),
    evictCallback: (key, value, reason) => false
);

Full configuration (callback) ​

csharp
var cache = new SlidingCache<TKey, TValue>(
    slidingTtl,
    maxEntries,
    trimEveryNAdds,
    minPruneInterval: TimeSpan.FromSeconds(30),
    evictCallback: (key, value, reason) => false
);

Disposal & eviction callback ​

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

Eviction callback signature:

csharp
Func<TKey, TValue, SlidingCacheEvictionReason, bool>

Return value:

  • true → callback assumes ownership (cache will NOT dispose)
  • false → cache disposes if value is IDisposable

Evictions are guarded by Entry.TryMarkDisposed() to prevent double-dispose during races.

Eviction reasons used by this implementation include:

  • Expired
  • Removed
  • Replaced
  • Size

Callback exceptions are swallowed (by design): an eviction callback must not destabilize cache operations.

Properties ​

Count ​

Count of objects in the sliding cache

MinimalPruneIntervalDefault ​

Default is 1 minute.

Methods ​

TryGetValue(key, out TValue value) ​

Behavior:

  • hit refreshes last-access tick and queues the key for recency tracking
  • expired entries are removed and disposed (if applicable)
  • triggers opportunistic prune

GetOrAdd(key, k => CreateValue(k) ​

Behavior under races:

if multiple threads create values for the same key, only one value is stored

losing created values are disposed immediately if TValue : IDisposable

SetSet(key, value) ​

Behavior:

  • replaces existing value if present (disposing prior value unless callback claims ownership)
  • otherwise adds new entry
  • triggers opportunistic prune

TryRemove(key) ​

If removed:

  • disposal occurs unless callback claims ownership

Trim() ​

Forces an immediate prune pass:

  • expiration checks (queue-bounded unless forced)
  • size enforcement eviction

Performance notes (what this design optimizes for) ​

  • Lock-free fast path for reads/writes via ConcurrentDictionary
  • Approximate LRU via queues (no global lock / no linked list bookkeeping)
  • Bounded prune budgets to avoid long pauses:
  • normal prune budgets are capped (e.g., 1024–8192 checks, eviction up to 2048 per pass)
  • forced trim can process more aggressively

Behavioral edge cases to understand ​

  • Because recency is tracked via queues, an entry can appear multiple times; Entry.TryMarkQueued() and ClearQueued() reduce duplicates, but this is still approximate.
  • Expiration is checked on access and during prune passes. Under heavy contention, expired entries may persist briefly until observed.
  • Time uses Environment.TickCount64 — expiration is robust to wall-clock changes, but it is not suitable for correlating to real time.