ASP. Net File Cache dependency
usingSystem;usingSystem.Collections.Generic;usingSystem.Linq;usingsystem.web;usingSystem.Web.UI;usingSystem.Web.UI.WebControls; Public Partial classdefault4:system.web.ui.page{/// <summary> ///Gets the cache object value for the current application specified CacheKey/// </summary> /// <param name= "CacheKey" >index key value</param> /// <returns>Returning cached Objects</returns> Public Static ObjectGetCache (stringCacheKey) {System.Web.Caching.Cache Objcache=Httpruntime.cache; returnObjcache[cachekey]; } /// <summary> ///set caching data in a cache-dependent way/// </summary> /// <param name= "CacheKey" >index key value</param> /// <param name= "Objobject" >Cache Objects</param> /// <param name= "Cachedepen" >Dependent Objects</param> Public Static voidSetcache (stringCacheKey,ObjectObjobject, System.Web.Caching.CacheDependency DEP) {System.Web.Caching.Cache Objcache=Httpruntime.cache; Objcache.insert (CacheKey, Objobject, DEP, Sys Tem. Web.Caching.Cache.NoAbsoluteExpiration,//never ExpiresSystem.Web.Caching.Cache.NoSlidingExpiration,//Disable Adjustable expirationSystem.Web.Caching.CacheItemPriority.Default,NULL); } protected voidPage_Load (Objectsender, EventArgs e) { stringCacheKey ="cachetest"; ObjectObjmodel =GetCache (CacheKey); //getting from the cache if(Objmodel = =NULL)//not in the cache.{Objmodel= DateTime.Now;//cache the current time if(Objmodel! =NULL) { //rely on changes to the C:\\Test.txt file to update the cacheSystem.Web.Caching.CacheDependency dep =NewSystem.Web.Caching.CacheDependency ("C:\\Test.txt"); Setcache (CacheKey, Objmodel, DEP);//Write Cache}} Label1.Text=objmodel.tostring (); }}
When we change the content of Test.txt , the cache is automatically updated. This is a good way to read the cache processing of a configuration file. If the configuration file does not change, the cached information is read all the time, and once the configuration changes, the synchronized cached data is automatically updated.
The disadvantage of this approach is that if you cache more data, the dependent files are relatively loose, and you have some trouble managing these dependent files. For a load-balanced environment, it is also necessary to update the cache files under multiple Web servers at the same time, which can be avoided if the cache in multiple Web applications relies on the same shared file.
ASP. Net File Cache dependency