ASP.NET缓存数据技巧三则

ASP.NET缓存数据技巧:访问缓存的值  由于缓存中所存储的信息为易失信息,即该信息可能由 ASP.NET 移除,因此建议先确定该项是否在缓存中。如果不在,则应将它重新添加到缓存中,然后检索该项。
  string cachedString;
  if
  (Cache["CacheItem"] != null)
  {
  cachedString = (string)Cache["CacheItem"];
  }
  else {
  //缓存不存在时
  Cache.Insert("CacheItem", "Hello, World.")
  cachedString = (string)Cache["CacheItem"];
  }
  ASP.NET缓存数据技巧:删除缓存项
  由于以下任一原因,缓存中的数据可能会自动移除:缓存已满、该项已过期、依赖项发生更改。注意:如果调用 Insert 方法,并向缓存中添加与现有项同名的项,则将从缓存中删除该旧项。显示删除缓存的值:
  Cache.Remove("MyCacheKey");
  ASP.NET缓存数据技巧:删除缓存项时通知应用程序
  从缓存中移除项时通知应用程序,可能非常有用。例如,可能具有一个缓存的报告,创建该报告需花费大量的时间进行处理。当该报告从缓存中移除时,希望重新生成该报告,并立即将其置于缓存中,以便下次请求该报告时,用户不必等待对此报告进行处理。
  ASP.NET 提供了CacheItemRemovedCallback 委托,在从缓存中移除项时能够发出通知。还提供 CacheItemRemovedReason 枚举,用于指定移除缓存项的原因。举例:假设有一个 ReportManager 对象,该对象具有两种方法,即 GetReport 和 CacheReport.GetReport 报告方法检查缓存以查看报告是否已缓存;如果没有,该方法将重新生成报告并将其缓存。CacheReport 方法具有与 CacheItemRemovedCallback 委托相同的函数签名;从缓存中移除报告时,ASP.NET 会调用 CacheReport 方法,然后将报告重新添加到缓存中。
  1)创建一个 ASP.NET 网页,该网页将调用类中用于将项添加到缓存中的方法。
  protected void Page_Load(object sender, EventArgs e)
  {
  this.Label1.Text = ReportManager.GetReport();
  }
  2)创建用于在从缓存中删除项时处理通知的完整类ReportManager.
  using System;
  using System.Web;
  using System.Web.Caching;
  public static class ReportManager
  {
  private static bool _reportRemovedFromCache = false;
  static ReportManager() { }
  //从缓存中获取项
  public static String GetReport()
  {
  lock (typeof(ReportManager))
  {
  if (HttpContext.Current.Cache["MyReport"] != null)
  {
  //存在MyReport缓存项,返回缓存值
  return (string)HttpRuntime.Cache["MyReport"];
  }
  else
  {   //MyReport缓存项不存在,则创建MyReport缓存项
  CacheReport();
  return (string)HttpRuntime.Cache["MyReport"];
  }
  }
  }
  //将项以 MyReport 的名称添加到缓存中,并将该项设置为在添加到缓存中后一分钟过期。
  //并且该方法注册 ReportRemoveCallback 方法,以便在从缓存中删除项时进行调用。
  public static void CacheReport()
  {
  lock (typeof(ReportManager))
  {
  HttpContext.Current.Cache.Add("MyReport",
  CreateReport(), null, DateTime.MaxValue,
  new TimeSpan(0, 1, 0),
  System.Web.Caching.CacheItemPriority.Default,
  ReportRemovedCallback);
  }
  }
  //创建报告,该报告时MyReport缓存项的值
  private static string CreateReport()
  {
  System.Text.StringBuilder myReport =
  new System.Text.StringBuilder();
  myReport.Append("Sales Report< br />");
  myReport.Append("2005 Q2 Figures< br />");
  myReport.Append("Sales NE Region - $2 million< br />");
  myReport.Append("Sales NW Region - $4.5 million< br />");
  myReport.Append("Report Generated: " + DateTime.Now.ToString()
  + "< br />");
  myReport.Append("Report Removed From Cache: " +
  _reportRemovedFromCache.ToString());
  return myReport.ToString();
  }
  //当从缓存中删除项时调用该方法。
  public static void ReportRemovedCallback(String key, object value,
  CacheItemRemovedReason removedReason)
  {
  _reportRemovedFromCache = true;
  CacheReport();
  }
  }
  不应在 ASP.NET 页中实现回调处理程序,因为在从缓存中删除项之前该页可能已被释放,因此用于处理回调的方法将不可用,应该在非ASP.NET的程序集中实现回调处理程 序。为了确保从缓存中删除项时处理回调的方法仍然存在,请使用该方法的静态类。但是,静态类的缺点是需要保证所有静态方法都是线程安全的,所以使用lock关键字。