Search code examples
c#caching.net-4.8

Get Absolute Expiration event from ObjectCache


I'm using an ObjectCache object as MemoryCache.Default (System.Runtime.Caching) and my policy contains AbsoluteExpiration.

for example:

ObjectCache cache = MemoryCache.Default
cahce.Add(key, reading, new CacheItemPolicy { AbsoluteExpiration = DateTimeOffset.Now.AddSeconds(20)});

I would like to save the objects before it's being removed.

Is it possible to catch the event of expiration, before item removed from cache?


Solution

  • When you add an Entry in MemoryCache with Add function, you can add CacheItemPolicy.

    This class have this fields:

         private DateTimeOffset _absExpiry;
            private TimeSpan _sldExpiry;
            private Collection<ChangeMonitor> _changeMonitors;
            private CacheItemPriority _priority;
            private CacheEntryRemovedCallback _removedCallback;
            private CacheEntryUpdateCallback _updateCallback;
    

    What you need is _removedCallback.

    Source code: here and here.