Skip to content

PostEvictionCallbacks does not get invoked when MemoryCache entries expire with an active change token #46774

@pranavkm

Description

@pranavkm

Observed as part of a runtime update: dotnet/aspnetcore#29153

Scenario:

using System;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.Extensions.Caching.Memory;

namespace cache_repro
{
    class Program
    {
        static bool _evicted;

        static async Task Main(string[] args)
        {
            var cache = new MemoryCache(new MemoryCacheOptions());
            var key = new object();

            var cts = new CancellationTokenSource(TimeSpan.FromSeconds(2));

            cache.Set(key, new object(), new MemoryCacheEntryOptions
            {
                ExpirationTokens = { new Microsoft.Extensions.Primitives.CancellationChangeToken(cts.Token) },
                PostEvictionCallbacks = { new PostEvictionCallbackRegistration { EvictionCallback = OnEntryEvicted } },
            });

            System.Console.WriteLine(cache.TryGetValue(key, out _));

            await Task.Delay(TimeSpan.FromSeconds(5));
            System.Console.WriteLine(cache.TryGetValue(key, out _));
            System.Console.WriteLine($"Evicted: {_evicted}");
        }

        static void OnEntryEvicted(object key, object value, EvictionReason reason, object state)
        {
            _evicted = true;
        }
    }
}

Using 5.0.0 version of Microsoft.Extensions.Caching.Memory, the post eviction callback is invoked when the CTS expires and causes the cache entry to be evicted. Using 6.0.0-alpha.1.21057.11, the callback no longer get invoked.

Metadata

Metadata

Assignees

Type

No type

Projects

No projects

Milestone

Relationships

None yet

Development

No branches or pull requests

Issue actions