Using Sliding Expiration
To utilize the APIs, include the following namespace in your application:
Alachisoft.NCache.Web.Caching.
Adding a New Item with Sliding Expiration
In the following example, the Add Operation is used to add a new item with the Sliding Expiration time period defined. The expiration time period is set by using the TimeSpan class. Also if the Sliding Expiration method is being used, NoAbsoluteExpiration needs to be explicitly declared in the parameters.
try {
// adding sliding expiration of 5 min through Add API.
cache.Add(key, product, null, Cache.NoAbsoluteExpiration, new TimeSpan(0, 5, 0), CacheItemPriority.Default);
// adding Default Sliding expiration with configured value
cache.Add(key, product, null, Cache.NoAbsoluteExpiration, Cache.DefaultSliding, CacheItemPriority.Default);
// adding SlidingLonger expiration with configured value
cache.Add(key, product, null, Cache.NoAbsoluteExpiration, Cache.DefaultSlidingLonger, CacheItemPriority.Default);
}
catch (Exception ex){
// handle exception
}
Updating Item with Sliding Expiration
In the following example the insert
Operation is used to add/update a Sliding
Expiration time period to an item already added to the cache. The expiration
time period is set by using the TimeSpan
class.
try
{
//updating sliding expiration of 5 min through Insert API.
cache.Insert(key, product, null, Cache.NoAbsoluteExpiration, new TimeSpan(0, 5, 0), CacheItemPriority.Default);
//updating Default Sliding expiration with configured value
cache.Add(key, product, null, Cache.NoAbsoluteExpiration, Cache.DefaultSliding, CacheItemPriority.Default);
//updating SlidingLonger expiration with configured value
cache.Add(key, product, null, Cache.NoAbsoluteExpiration, Cache.DefaultSlidingLonger, CacheItemPriority.Default);
}
catch (Exception ex){
// handle exception
}
Setting Sliding Expiration with CacheItem
In the following example, Sliding Expiration time period is set by assigning it
as a property of a CacheItem
object.
// Setting sliding expiration of 10 seconds.
cacheItem.SlidingExpiration = new TimeSpan(0, 0, 10);
string key = "Product:" + product.ProductID;
try{
cache.Add(key, cacheItem, DSWriteOption.None, null);
}
catch (Exception ex){
// handle exception
}