您的位置:首页 > 其它

缓存应用程序数据(二)

2009-02-12 00:09 204 查看
二、访问缓存的值

由于缓存中所存储的信息为易失信息,即该信息可能由 ASP.NET 移除,因此建议先确定该项是否在缓存中。如果不在,则应将它重新添加到缓存中,然后检索该项。

Code

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关键字。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: