ASP.NET Caching & Renew Caching Item

ASP.NET Caching & Renew Caching Item

   index.aspx
 
   Cache 1 : <asp:Label ID="Cache1" runat="server" Text="" /><br />
   Cache 2 : <asp:Label ID="Cache2" runat="server" Text="" /><br /><br />
 
   <asp:Button ID="ClearCacheBtn" runat="server" Text="Clear Cache" OnClick="ClearCacheBtn_Click" />
 
   index.aspx.cs
 
   using System;
   using System.Web;
   using System.Web.UI;
   using System.Runtime.Caching;
 
   protected void Page_PreRender(object sender, EventArgs e)
   {
      ObjectCache cache = MemoryCache.Default;
 
      if (cache["Cache1"] == null)
         cache.Set("Cache1", System.DateTime.Now.ToLongTimeString(), getCacheItemPolicy(30));
 
      if (cache["Cache2"] == null)
         cache.Set("Cache2", System.DateTime.Now.ToLongTimeString(), getCacheItemPolicy(30));
 
      Cache1.Text = cache["Cache1"].ToString();
      Cache2.Text = cache["Cache2"].ToString();
   }
 
   public CacheItemPolicy getCacheItemPolicy(int ExpiryTimeSec)
   {
      CacheItemPolicy policy = new CacheItemPolicy();
      policy.AbsoluteExpiration = DateTimeOffset.Now.AddSeconds(ExpiryTimeSec);
 
      return policy;
   }
 
   protected void ClearCacheBtn_Click(object sender, EventArgs e)
   {
      ObjectCache cache = MemoryCache.Default;
      cache.Remove("Cache2");
   }