.NET 7 MemoryCache Statistics 4

After we have finished displaying memorycache entries, we can also track it’s statistics by using MemoryCacheStatistics which is included in .NET 7.

We will modify our CacheBase.cs first. Need a method that invokes GetCurrentStatistics()

public MemoryCacheStatistics GetStats()
   return _cache.GetCurrentStatistics();            

It will return MemoryCacheStatistics which has useful properties such as; TotalHits, TotalMisses

Everytime reading from cache will increase TotalHits, If there is no matching cache entries it will increase TotalMisses.

In our design, if there is no cache entry it will call ReloadCache. So we will see that both will increase at the same time.

Let’s write a new endpoint that returns GetStats()

public IActionResult GetStats(string key)
    string typeName = $"webappart.{key}"; // replace namespace with yours
    Type type = Type.GetType(typeName);
    if (type == null)
       return null;

    dynamic service = provider.GetService(type);
    var stats = service.GetStats();
    return Ok(stats);

With 15 seconds of AbsoulteExpiration. First attempt looks like this,


We have to set TrackStatistics property when we are registering MemoryCache!

builder.Services.AddMemoryCache(options => { options.TrackStatistics = true; });

After we have done it we can try again,

We need to call cache items when they were expired. So let’s decrease AbsoulteExpiration to 1 seconds in ConfigurationCache.cs

protected override MemoryCacheEntryOptions SetPolicy()
    MemoryCacheEntryOptions options = new MemoryCacheEntryOptions();
    options.AbsoluteExpiration = DateTime.Now.AddSeconds(1); // here
    return options;

And after I have executed every seconds to api/Cache/Get

We have some misses,

This statistics can be a guide for using memory cache properly. If there is a lot of misses, your AbsoluteExpiration might be low or this cache should use SlidingExpiration instead.