Class TimedCache<TKey, TValue>
- Namespace
- FishMMO.Server.Core.Collections
- Assembly
- FishMMO.Server.dll
A thread-safe, write-through TTL cache where entries expire after a fixed duration from when they were stored. Reads do NOT extend the lifetime (unlike LastSeenCacheTracker<TKey, TValue>).
Supports bounded head-first SweepExpired(TimeSpan, int, int) for memory management.
Ages are measured on MonotonicClock, not the host's wall clock. A TTL is a
duration, and on DateTime.UtcNow a clock stepped back an hour kept every entry
"fresh" for that hour: the world server's available-scene cache served the same instance
list, populations and all, long after the instances had filled or gone.
public sealed class TimedCache<TKey, TValue>
Type Parameters
TKeyCache key type.
TValueCache value type.
- Inheritance
-
TimedCache<TKey, TValue>
- Inherited Members
Constructors
TimedCache(IEqualityComparer<TKey>)
Initializes a new cache with an optional key comparer.
public TimedCache(IEqualityComparer<TKey> comparer = null)
Parameters
comparerIEqualityComparer<TKey>
Methods
Clear()
Clears all cached entries.
public void Clear()
Invalidate(TKey)
Removes a single cached entry.
public void Invalidate(TKey key)
Parameters
keyTKeyCache key to invalidate.
Set(TKey, TValue)
Stores or overwrites a value, stamped with the current MonotonicClock reading.
public void Set(TKey key, TValue value)
Parameters
keyTKeyCache key.
valueTValueValue to cache.
SweepExpired(TimeSpan, int, int)
Sweeps entries older than the specified TTL using bounded head-first traversal.
public int SweepExpired(TimeSpan ttl, int maxScan, int maxRemove)
Parameters
ttlTimeSpanEntries older than this duration are eligible for removal.
maxScanintMaximum queue nodes to inspect this sweep.
maxRemoveintMaximum entries to remove this sweep.
Returns
- int
Number of entries removed.
Remarks
Reads the clock itself rather than taking a "now": the entries were stamped by Set(TKey, TValue) on MonotonicClock, and a caller-supplied instant from any other clock would compare two unrelated numbers.
TryGet(TKey, TimeSpan, out TValue)
Tries to retrieve a cached value that was stored within the specified TTL. Does NOT refresh the stored timestamp — entries always expire relative to the time they were written via Set(TKey, TValue).
public bool TryGet(TKey key, TimeSpan ttl, out TValue value)
Parameters
keyTKeyCache key.
ttlTimeSpanMaximum age for the entry to be considered valid.
valueTValueThe cached value if found and still valid.
Returns
- bool
trueif a valid (non-expired) entry was found.