访问缓存的值由于缓存中所存储的信息为易失信息,即该信息可能由ASP.NET移除,因此建议先确定该项是否在缓存中。如果不在,则应将它重新添加到缓存中,然后检索该项。下面学步园小编来讲解下ASP.NET缓存数据有哪些技巧?
ASP.NET缓存数据有哪些技巧
stringcachedString;
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方法,然后将报告重新添加到缓存中。
ASP.NET缓存数据有哪些技巧
1)创建一个ASP.NET网页,该网页将调用类中用于将项添加到缓存中的方法。
protectedvoidPage_Load(objectsender,EventArgse)
{
this.Label1.Text=ReportManager.GetReport();
}
2)创建用于在从缓存中删除项时处理通知的完整类ReportManager.
usingSystem;
usingSystem.Web;
usingSystem.Web.Caching;
publicstaticclassReportManager
{
privatestaticbool_reportRemovedFromCache=false;
staticReportManager(){}
//从缓存中获取项
publicstaticStringGetReport()
{
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方法,以便在从缓存中删除项时进行调用。
publicstaticvoidCacheReport()
{
lock(typeof(ReportManager))
{
HttpContext.Current.Cache.Add("MyReport",
CreateReport(),null,DateTime.MaxValue,
newTimeSpan(0,1,0),
System.Web.Caching.CacheItemPriority.Default,
ReportRemovedCallback);
}
}
//创建报告,该报告时MyReport缓存项的值
privatestaticstringCreateReport()
{
System.Text.StringBuildermyReport=
newSystem.Text.StringBuilder();
myReport.Append("SalesReport
");
myReport.Append("2005Q2Figures
");
myReport.Append("SalesNERegion-$2million
");
myReport.Append("SalesNWRegion-$4.5million
");
myReport.Append("ReportGenerated:"+DateTime.Now.ToString()
+"
");
myReport.Append("ReportRemovedFromCache:"+
_reportRemovedFromCache.ToString());
returnmyReport.ToString();
}
//当从缓存中删除项时调用该方法。
publicstaticvoidReportRemovedCallback(Stringkey,objectvalue,
CacheItemRemovedReasonremovedReason)
{
_reportRemovedFromCache=true;
CacheReport();
}
}
不应在ASP.NET页中实现回调处理程序,因为在从缓存中删除项之前该页可能已被释放,因此用于处理回调的方法将不可用,应该在非ASP.NET的程序集中实现回调处理程序。为了确保从缓存中删除项时处理回调的方法仍然存在,请使用该方法的静态类。但是,静态类的缺点是需要保证所有静态方法都是线程安全的,所以使用lock关键字。
以上就是关于“ASP.NET缓存数据有哪些技巧”的内容,希望对大家有用。更多资讯请关注学步园。学步园,您学习IT技术的优质平台!