Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

.NET Caching how does Sliding Expiration work?

Tags:

c#

.net

caching

If I use an ObjectCache and add an item like so:

ObjectCache cache = MemoryCache.Default; string o = "mydata"; cache.Add("mykey", o, DateTime.Now.AddDays(1)); 

I understand the object will expire in 1 day. But if the object is accessed 1/2 a day later using:

object mystuff = cache["mykey"]; 

Does this reset the timer so it's now 1 day since the last access of the entry with the key "mykey", or it still 1/2 a day until expiry?

If the answer is no is there is a way to do this I would love to know.

Thanks.

like image 246
Kelly Avatar asked Nov 30 '12 01:11

Kelly


People also ask

What is sliding expiration in caching?

Sliding expiration ensures that if the data is accessed within the specified time interval the cache item life span will be extended by the interval value. For example, a session is added with 10 minutes expiration.

How does sliding expiration work?

Sliding expiration resets the expiration time for a valid authentication cookie if a request is made and more than half of the timeout interval has elapsed. If the cookie expires, the user must re-authenticate.

What is sliding expiration and absolute expiration in caching?

Sliding ExpirationIn Absolute Expiration the cache will be expired after a particular time irrespective of the fact whether it has been used or not in that time span. Whereas, in Sliding Time Expiration, the cache will be expired after a particular time only if it has not been used during that time span.

What is the default time span value for the Cacheitempolicy Slidingexpiration property under which a cache entry must be accessed before it is expelled from the cache?

A span of time within which a cache entry must be accessed before the cache entry is evicted from the cache. The default is NoSlidingExpiration, meaning that the item should not be expired based on a time span.


1 Answers

There are two types of cache policies you can use:

CacheItemPolicy.AbsoluteExpiration will expire the entry after a set amount of time.

CacheItemPolicy.SlidingExpiration will expire the entry if it hasn't been accessed in a set amount of time.

The ObjectCache Add() overload you're using treats it as an absolute expiration, which means it'll expire after 1 day, regardless of how many times you access it. You'll need to use one of the other overloads. Here's how you'd set a sliding expiration (it's a bit more complicated):

CacheItem item = cache.GetCacheItem("item");  if (item == null) {      CacheItemPolicy policy = new CacheItemPolicy {         SlidingExpiration = TimeSpan.FromDays(1)     }      item = new CacheItem("item", someData);      cache.Set(item, policy); } 

You change the TimeSpan to the appropriate cache time that you want.

like image 56
mfanto Avatar answered Sep 21 '22 14:09

mfanto