Tracking linked cache entries

MemoryCache tracks linked cache entries so that options are propagated. In the following example, the expirationToken added for child is also applied to parent:

using (var parent = cache.CreateEntry(key))
{
    parent.SetValue(obj);

    using (var child = cache.CreateEntry(key1))
    {
        child.SetValue(obj);
        child.AddExpirationToken(expirationToken);
    }
}

For performance reasons, .NET 7 no longer tracks linked cache entries by default. However, you can enable tracking using a new option.

Version introduced

.NET 7

Previous behavior

Prior to .NET 7, MemoryCache tracked linked cache entries to allow for options to be propagated. The tracking could not be disabled.

New behavior

Starting in .NET 7, MemoryCache does not track linked cache entries, by default. The MemoryCacheOptions.TrackLinkedCacheEntries option was added so you can control whether linked cache entries are tracked or not.

Type of breaking change

This change can affect binary compatibility.

Reason for change

This change was introduced to improve performance. Tracking internally uses AsyncLocal<T>, which is expensive and adds non-trivial overhead.

If you want MemoryCache to continue tracking linked cache entries so options can be propagated, set MemoryCacheOptions.TrackLinkedCacheEntries to true.

var options = new MemoryCacheOptions
{
    TrackLinkedCacheEntries = true
};

var cache = new MemoryCache(options);

Affected APIs