Write for Us
The following is the complete syntax of using the CacheDependency class.
CacheDependency cacheDependency = new CacheDependency(fileObj, dateTimeObj);Cache.Insert(key, value, cacheDependency);
As an example, you can set Cache dependency to an external Xml file as shown below:--
Cache.Insert("Country", objDataSet, new CacheDependency(Server.MapPath("Country.xml")));
You can also set a Cache dependency to a file in a remote system as shown below:--
CacheDependency objCacheDependency = new CacheDependency(@"\\192.168.0.9\joydipk\Test.txt");
Similarly, you can also set Cache dependency on an entire folder. When the contents of the folder changes it will call an event handler for which you need to write the necessary code. In the earlier version of ASP.NET, the CacheDependency class was sealed. Hence you could not subclass this class to create your own Custom Cache dependencies. Things have now changed with ASP.NET 2.0 and the class is no longer sealed so you can create Custom Cache Dependencies by extending this class.
Cache Expiration relates to the removal of data in the cache after the durability of the cached item in the cache has expired. Cache expirations strategies can be Time Based, File Based or Key Based. The following sections discuss each of these strategies in detail with code examples.
Response.Cache.SetExpires(DateTime.Now.AddSeconds(45));
This can also be accomplished by specifying the following in the page output cache directive as shown here.
<%@OutputCache Duration="45"VaryByParam="None" %>
Time based expiration strategies can in turn be of the following two types:
Absolute Sliding
In Absolute Expiration, the cache expires at a fixed time/date. For Sliding Expiration the cache duration is increased by the specified sliding expiration value each time the page is requested. Thus a heavily requested page will remain cached, whereas a less requested page will not be cached. Sliding Expiration is therefore useful in ensuring that the valuable resources allocated to the cache are allocated to the most heavily requested pages/items.
The following is an example of Absolute Expiration:
Cache.Insert("Country", ds, null, DateTime.Now.AddMinutes(1), Cache.NoSlidingExpiration);
The cache is set to expire exactly two minutes after the user has retrieved the data.
The following is an example of Sliding Expiration:
Cache.Insert("Country", ds, null, Cache.NoAbsoluteExpiration, TimeSpan.FromMinutes(1));
Note that you cannot use both Absolute and Sliding expirations at the same time.