ALLINSIGHT

Home of the AlmostImplementedException

How to use SlidingExpiration AND AbsoluteExpiration at the same time

As I mentioned in the last post, you can’t use SlidingExpiration and AbsoluteExpiration a the same time. Thats by design. Thanks again, Microsoft.
But there is a workaround. First i will present the solution and then a short and easy way to use it.

The ObjectCache / MemoryCache has a nice little function called CreateCacheEntryChangeMonitor. This method takes one or more keys and gives you a CacheEntryChangeMonitor. The nice thing is, you don’t need to do anything with this monitor. You can use it on a CacheItemPolicy and link two cache-entries together.
And we use this, to link a SlidingExpiration and AbsoluteExpiration. There is one setback, you need two objects in cache for this and that makes it a little tricky (only a little)

At first glance it might look complicated, but it isn’t. The first 2 lines declare both keys we need. After that we create the first object which uses AbsoluteExpiration. In our case 60 seconds. The value that we cache is an emtpy object, because we don’t need it.

After that we create a monitor for this object. And then we create the second, and real cache-object. This time with a SlidingExpiration of 10 seconds. The second object add the monitor to its own and thats it.

Now we have both expirations at the same time. If the object isn’t used every 10 seconds it will expire. But after 60 second it expires anyway.

But you have to do one more trick for this to work. At least for short caching times. The expiration event isn’t firing exactly on the expiration-time. It may take several second to fire. Because of that you have to check both expirations and the AbsolutExpiration first, like this:

And now to the part that makes our life easier. Again we’ll use extension-methods, but this time we’ll extend the ObjectCache.
First we need a method to add an item with both expirations to the cache

Its the same as above, but as an extension method. And of course, we need a method to check if the object is expired.

Easy peasy. And here is a little example on how to use it:

Share :

, , ,

Leave a Reply

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