0

Using .NET 5.0 and ASP.net, I'm trying to (ab)use MemoryCache to regularly run a service. To test, I've written the following code

using Microsoft.Extensions.Caching.Memory;
[...]
public sealed class MyService : IMyService
{
    private readonly IMemoryCache _cache;

    public MyService(IMemoryCache cache)
    {
        _cache = cache;

        SetTimer();
    }

    private void SetTimer()
    {
        _cache.Set(nameof(MyService), $"Starts every 30 seconds.", new MemoryCacheEntryOptions()
            .SetAbsoluteExpiration(TimeSpan.FromSeconds(30))
            .RegisterPostEvictionCallback((_, _, _, _) =>
            {
                Task.Run(async () => await MyTask()).ConfigureAwait(false);
            }));
    }
    
    public async Task MyTask() {...}

The (singleton)service is correctly started and SetTimer runs, but after 30 seconds (expiration) the callback is not called (I set a breakpoint in the lanmda and in MyTask, and neither is triggered)... I've checked the keys and AbsoluteExpiration is set correctly.

I saw this answer is the same thing happening here (thread sleeping)?

JHBonarius
  • 10,824
  • 3
  • 22
  • 41
  • 3
    [This post](https://stackoverflow.com/questions/42535408/net-core-memorycache-postevictioncallback-not-working-properly) seems to explain it: `the item is not evicted till you query for the item and it checks the expiration`. There's also [an answer](https://stackoverflow.com/a/47949111/5803406) showing a solution passing an expiring cancellation token to the cache – devNull Jan 13 '21 at 20:22
  • Why not just use an actual async timer? – David L Jan 13 '21 at 20:44
  • There's also a note in the [docs](https://learn.microsoft.com/en-us/aspnet/core/performance/caching/memory?view=aspnetcore-5.0#additional-notes) for this. – Kirk Larkin Jan 13 '21 at 21:57
  • @devNull Yes, thanks! I'm stumped... I spend quite some time searching for this, especially on StackOverflow. But that question/answer never popped up in the seach results. No idea what I did wrong. Hope this dupe will help others like me out. – JHBonarius Jan 14 '21 at 07:38

0 Answers0