In ASP.NET Core's IMemoryCache, what do RegisterPostEvictionCallback and AddExpirationToken do, and when does an eviction callback actually run?
answer
- PostEvictionDelegate(key, value, reason, state)
- EvictionReason: Removed, Replaced, Expired, TokenExpired, Capacity
- runs on the thread pool, after removal
- CancellationChangeToken evicts a group at once
- TrackLinkedCacheEntries false since .NET 7
basics
~20 sRegisterPostEvictionCallback runs a delegate on the thread pool after an entry leaves the cache, with an EvictionReason. AddExpirationToken ties the entry to an IChangeToken, such as a CancellationChangeToken, whose firing queues its eviction at once.
solid answer
~40 s`RegisterPostEvictionCallback` attaches a `PostEvictionDelegate(object key, object? value, EvictionReason reason, object? state)` that runs **after** the entry is removed, on a thread-pool task rather than the caller's thread; an exception it throws is logged and swallowed. The reason is `Removed`, `Replaced`, `Expired`, `TokenExpired` or `Capacity`. Time-based expiry is noticed lazily, on access or during the periodic scan, so an `Expired` callback can run long after the deadline or not until something touches the cache. `AddExpirationToken` attaches an `IChangeToken`; a `CancellationChangeToken` over a `CancellationTokenSource` queues the entry's removal as soon as `Cancel()` is called, which makes it the tool for evicting a group, such as every rate from one provider. In .NET 10 `TrackLinkedCacheEntries` is off by default, so an outer entry no longer picks up the tokens of entries created or read inside its factory.
code
csharp · 11 linesvar options = new MemoryCacheEntryOptions()
.SetAbsoluteExpiration(TimeSpan.FromSeconds(30))
.RegisterPostEvictionCallback((key, value, reason, state) =>
{
if (reason is EvictionReason.Replaced)
return;
var log = (ILogger)state!;
log.LogInformation("Rate {Key} evicted: {Reason}", key, reason);
}, logger);
cache.Set("fx:USD:MXN", 17.25m, options);go deeper
Recall that an eviction callback reports a key, value and EvictionReason, and that an expiration token lets external code evict an entry by firing a signal.
Explain the five reasons, that callbacks run on the thread pool after removal with exceptions logged, and how a CancellationChangeToken evicts a whole group at once, without waiting for a read.
Explain why time-based callbacks fire late, why refresh-on-evict races with readers, and that TrackLinkedCacheEntries is off by default, so an outer entry needs inner entries' tokens passed explicitly.
Judge when signal-driven invalidation through tokens is worth its bookkeeping compared with short expirations, and where an in-process signal stops working once several instances cache the same data.
## Eviction callbacks An eviction callback is a `PostEvictionDelegate`: ```csharp public delegate void PostEvictionDelegate(object key, object? value, EvictionReason reason, object? state); ``` You attach one with `RegisterPostEvictionCallback` on `MemoryCacheEntryOptions` or on the `ICacheEntry` a factory receives (an overload takes a `state` object that is passed back to you). The `EvictionReason` tells you why the entry left: | Reason | Raised when | |---|---| | `Removed` | `Remove(key)` or `Clear()` was called | | `Replaced` | `Set` wrote a new entry for the same key | | `Expired` | an absolute or sliding expiration passed | | `TokenExpired` | an attached `IChangeToken` signalled a change | | `Capacity` | a size-limited cache rejected or compacted the entry | | `None` | the entry has not been evicted | Three implementation facts shape how callbacks behave in production: - **They run after removal, on the thread pool.** `MemoryCache` queues them with `Task.Factory.StartNew`, so they never run on the request thread that caused the eviction and they cannot veto it. - **Exceptions are swallowed.** A throwing callback is caught and logged as "EvictionCallback invoked failed"; nothing reaches the caller. - **Time-based eviction is noticed late.** There is no timer per entry. An entry whose deadline passed is removed when something reads it or when a background scan runs, and a scan starts only when a cache operation finds `ExpirationScanFrequency` (1 minute by default) has elapsed since the last one. A quiet cache can hold an expired entry, with its callback unfired, indefinitely. That last point is why "refresh the value from the eviction callback" is a weak design: the refresh happens at an unpredictable time after the deadline, fires for `Replaced` as well unless you filter on the reason, and races with requests that already missed and are reloading the same key. ## Expiration tokens `AddExpirationToken(IChangeToken)` makes an entry depend on an external signal. When the token reports `HasChanged`, the entry is expired with reason `TokenExpired`. For tokens whose `ActiveChangeCallbacks` is true - `CancellationChangeToken` is one - the cache registers a change callback that **queues the entry's removal on the thread pool as soon as the token fires**, without waiting for a read or a scan. The common use is **group eviction**. A remittance service caches one entry per currency pair, all fed by the same rate provider; when the provider pushes a new rate sheet, every pair from it must go: ```csharp private CancellationTokenSource _sheet = new(); public void CacheRate(string pair, decimal rate) => cache.Set($"fx:{pair}", rate, new MemoryCacheEntryOptions() .SetAbsoluteExpiration(TimeSpan.FromMinutes(5)) .AddExpirationToken(new CancellationChangeToken(_sheet.Token))); public void OnNewRateSheet() { var old = Interlocked.Exchange(ref _sheet, new CancellationTokenSource()); old.Cancel(); old.Dispose(); } ``` Every entry written with the old token is removed when `Cancel()` runs; entries written afterwards use the new source. ## Linked entries changed in .NET 7 `MemoryCacheOptions.TrackLinkedCacheEntries` controls whether an entry created **inside** another entry's factory (between `CreateEntry` and its disposal) copies its tokens and earlier absolute expiration up to the parent. The option's own documentation notes that before .NET 7 this was always on; it now defaults to **false**. Older articles, including parts of the ASP.NET Core caching page, still describe that propagation as automatic. In .NET 10 you either pass the tokens to each entry explicitly or turn the option on for that cache instance. ## Callback or token? | Need | Tool | |---|---| | Log, count or dispose something when an entry leaves | `RegisterPostEvictionCallback` | | Evict many entries together when an external event happens | `AddExpirationToken` with a shared `CancellationChangeToken` | | Evict one entry on a write | `Remove(key)` | | Know immediately that a time limit passed | neither; expiry is noticed lazily, so schedule the work yourself | The value passed to a callback is the evicted object, which makes callbacks a good place to dispose cached `IDisposable` resources once nothing can read them from the cache any more. ## The traps 1. **Assuming a callback fires on time.** For `Expired` it fires when the removal is noticed, not at the deadline. 2. **Ignoring the reason.** `Set` on an existing key raises `Replaced` for the old entry; a callback that reloads on every eviction reloads after every write. 3. **Doing slow work inline.** Callbacks share the thread pool with request processing; blocking calls in them cost throughput. 4. **Never disposing the old `CancellationTokenSource`.** Swap and dispose it, or each rate sheet leaves one behind.
- Can a post-eviction callback stop the eviction or put the old value back atomically?No. It runs on a thread-pool task after the entry has already been removed. It can call `Set` again, but that is an ordinary new write that races with requests which already missed, so it cannot restore the entry atomically.
- Why does cancelling a CancellationTokenSource remove entries without waiting for a read, while time expiry does not?`CancellationChangeToken` reports `ActiveChangeCallbacks` as true, so when the entry is committed the cache registers a change callback on it. Cancelling the source invokes that callback, which schedules removal right away. Time-based expiry has no such signal and is only evaluated on access or during a scan.
- An eviction callback runs synchronously on the request thread that removed the entry
- A time-expired entry's callback fires exactly at its expiration deadline
- Throwing from an eviction callback cancels the eviction and keeps the entry
- In .NET 10 an outer entry automatically inherits tokens from entries created inside its factory
- Calling Set on an existing key raises no eviction callback for the old entry
Assumes Microsoft.Extensions.Caching.Memory 10.0; since .NET 7 MemoryCacheOptions.TrackLinkedCacheEntries defaults to false, so an outer entry no longer inherits tokens and expiration from entries created or read inside its factory.