Using System; using System. collections. generic; using System. linq; using System. web; using System. web. UI; using System. web. UI. webControls; public partial class Default4: System. web. UI. page {// <summary> /// obtain the Cache object Value of the specified CacheKey in the current application. /// </summary> /// <param name = "CacheKey"> Index key value </param> /// <returns> returns the cache object </returns> public static object GetCache (string CacheKey) {System. web. caching. cache objCache = HttpRuntime. cache; return objCache [CacheKey];} /// <summary> /// set the index key value to cache dependent data /// </summary> /// <param name = "CacheKey">/ param> /// <param name = "objObject"> cache object </param> /// <param name = "cacheDepen"> dependency object </param> public static void SetCache (string CacheKey, object objObject, System. web. caching. cacheDependency dep) {System. web. caching. cache objCache = HttpRuntime. cache; objCache. insert (Cach EKey, objObject, dep, System. web. caching. cache. noAbsoluteExpiration, // never expires System. web. caching. cache. noSlidingExpiration, // disable the adjustable expiration System. web. caching. cacheItemPriority. default, null);} protected void Page_Load (object sender, EventArgs e) {string CacheKey = "cachetest"; object objModel = GetCache (CacheKey ); // obtain if (objModel = null) from the cache // No {objModel = DateTime in the cache. now; // cache the current time if (objModel! = Null) {// update the cache System based on the changes in the C: \ test.txt file. web. caching. cacheDependency dep = new System. 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 method is suitable for reading the cache of configuration files. If the configuration file does not change, the cached information will be read all the time. Once the configuration changes, the cached data will be automatically updated and synchronized.
The disadvantage of this method is that, if the cached data is large and the dependent files are loose, it is troublesome to manage these dependent files. In the Server Load balancer environment, you also need to update the cache files under multiple Web servers at the same time. If the cache of multiple Web applications depends on the same shared file, this problem may be avoided.