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)?