Alachisoft NCache 4.1 - Online Documentation

Expiring Cached Items

An expiration object can be associated with each item being added to the cache. When that expiration object invalidates (invalidation of expiration object depends on the provided parameters), the associated item is removed from the cache. NCache provides two types of expirations i.e. Absolute expiration and Sliding expiration.
Absolute Expiration:
Absolute Expiration is the time in which an added object expires and is removed from the cache.
Sliding Expiration:
Time interval between the last accessed time of the added object and object expiration time. If this interval is equal to 10 minutes, then object will expire and it will be removed from the cache 10 minutes after it is last accessed. If you are using absolute expiration, the slidingExpiration parameter must be NoSlidingExpiration.
Using Absolute and Sliding Expiration:
While adding some items to the cache, you can provide a DateTime value which is translated into Absolute Expiration and the item is removed from the cache at the specified DateTime value. If you don't want to provide any Absolute Expiration, you can use an enumeration (NoAbsoluteExpiration) provided by NCache. Similarly, you can provide a TimeSpan value which is translated into Sliding Expiration and item is removed from the cache if the specified period of time has elapsed since it was last accessed. If you don't want to provide a Sliding Expiration, you can use an enumeration (NoSlidingExpiration) provided by NCache.
Following is a step-by-step guide for using absolute and sliding expirations:
  1. Include the following namespaces in your application:
    using Alachisoft.NCache.Web.Caching;
    using Alachisoft.NCache.Runtime;
  2. Create a new Class named 'Customer' in your already created Test Application.
  3. Insert the following code in the 'Customer' class.
    class Customer
  4. Now insert the following code in the 'Main' of the project:
        Cache cache = NCache.InitializeCache("mycache");
        Customer customer1 = new Customer(); = "David";
        customer1.customerID = 1001;
        customer1.OrderPlaced = "C-11";
        customer1.City = "New York";
        CacheItem cItem1 = new CacheItem(customer1);
        //Adding Item with Absolute Expiration:
        cache.Add("Customer:David:1001", cItem1, null, System.DateTime.Now.AddSeconds(30), Cache.NoSlidingExpiration, CacheItemPriority.Normal);
        Customer customer2 = new Customer(); = "Alex";
        customer2.customerID = 1002;
        customer2.OrderPlaced = "C-10";
        customer2.City = "London";
        CacheItem cItem2 = new CacheItem(customer2);
        //Adding Item with Sliding Expiration:
        cache.Add("Customer:Alex:1002", cItem2, null, Cache.NoAbsoluteExpiration, new TimeSpan(0, 0, 30), CacheItemPriority.Default);
5. Start the Local Cache 'mycache'.
6. Run the project.
See Also
Copyright © 2005-2012 Alachisoft. All rights reserved.