Home of the AlmostImplementedException

Let cached objects expire with SlidingExpiration / AbsoluteExpiration

A while ago i wrote a post about the ObjectCache / MemoryCache and here is a little follow up.
The ObjectCache allow you to set an expiration on an object you put into it. Thats very useful since most objects are only valid for a short time. When you want to cache a result from a database-query it is clear you need a well-defined timeout. Or maybe you generate a report every day and want the cached report removed ate the same time every day.

AbsoluteExpiration allow you both things. You can set a DateTimeOffset to cache an object for a specific amount of time or you use DateTime to cache an object until this time is reached.

And here are 2 examples. The first one caches an object until 18:30 of the same day (after that the object expires immediately). The second one caches the object for 20 seconds.

When you want to cache a session, you need an expiration depending of the last usage. For that you can use SlidingExpiration.
To set a SlidingExpiration you have to define a TimeSpan. Every time the object is received / checked from the cache the timeout is set back. This example sets an expiration of 20 seconds and if the object is used within this 20 seconds you get another 20 seconds.

Unfortunately you can’t combine both. You have to choose either the AbsoluteExpiration, the SlidingExpiration or none. It would have come in handy for sure. Imagin a scenario where you want a SlidingExpiration to be sure the object is used frequently and on the other hand want to expire it after a specific amout of time or at a precise moment.

Maybe we’ll discuss this in a later post.

Another interesting thing about the CacheItemPolicy is RemovedCallback. It is called after an item is removed from the cache and can be used to monitor specific objects (like a session). But a word of warning! Don’t expect this method right after an item is expired!
The cache isn’t checking the expiration of an object every second.

In this example an object ist cached for 2 seconds. But you will notice that “Removed” isn’t printed for several more seconds.

And here a final, complete example to demonstrate the 3 different usecases. Just uncomment the expiration you want and see what happens.
When you use the first AbsoluteExpiration, you will see that RemovedCallback is called right before the second Containts-call. Because if you use an item, the cache checkes the expiration immediately.

Share :

, ,

Leave a Reply

Your email address will not be published. Required fields are marked *