Search code examples
.net-corememorycachelazycache

MemoryCache - both AbsoluteExpiration and SlidingExpiration


I am using LazyCache but it is built on MemoryCache and so I think this question is MemoryCache related.

As I understand it, when a MemoryCache is created, you cannot set expirations. You can set the polling interval, but expirations are never - correct?

So expirations are set when you call myCache.Add(item, policy) and therefore every cache entry has its own expiration.

I have some values where I want to set both an AbsoluteExpiration of 15 minutes and a SlidingExpiration of 20 seconds. So if the entry is being actively Get() it will live for 15 minutes, and then expire event if it's being requested every second. And it will also expire if 21 seconds go by with no request, even if that's under the 15 minute limit.

So what happens if both are set? The documentation is silent on that topic. With my testing I think it expires if either is hit, but I may not be testing right. And equally important - is that guaranteed going forward? Or is it an implementation detail that can change?


Solution

  • The source code shows it supports both, and will behave as expected.

    The documentation - while not overly explicit - does show the same:

    Here:

    A cached item set with only a sliding expiration is at risk of never expiring. If the cached item is repeatedly accessed within the sliding expiration interval, the item never expires. Combine a sliding expiration with an absolute expiration to guarantee the item expires. The absolute expiration sets an upper bound on how long the item can be cached while still allowing the item to expire earlier if it isn't requested within the sliding expiration interval. If either the sliding expiration interval or the absolute expiration time pass, the item is evicted from the cache.

    and here:

    MemoryCacheEntryExtensions.SetSlidingExpiration Method

    This will not extend the entry lifetime beyond the absolute expiration (if set).