Cache对象除了直接用Cache["xx"]直接存取数据以外,它还有四个Cache.Insert()方法重载,这在前面的文章中有介绍, 这里仅是为了练习一下,来对其中几种较为常用的用法来加以使用,其它有绝对到期,滑动到期,以及文件依赖到期:
不说其它的了,下面是代码:
using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
public partial class Default2 : System.Web.UI.Page
{
static string reason1 = string.Empty;
protected void Page_Load(object sender, EventArgs e)
{
//绝对到期:此示例将对受时间影响的数据缓存半分钟,半分钟过后,缓存将到期。注意,绝对到期和滑动到期(见下文)不能一起使用。
object myTimeSensitiveData;
object myFrequentlyAccessedData;
if (!IsPostBack)
{
string tt = "绝对到期";
myTimeSensitiveData = (object)tt;
Cache.Insert("key", myTimeSensitiveData, null, DateTime.Now.AddSeconds(30), TimeSpan.Zero);
//滑动到期:此示例将缓存一些频繁使用的数据。数据将在缓存中一直保留下去,除非数据未被引用的时间达到了半分钟。注意,滑动到期和绝对到期不能一起使用。
string cc = "滑动到期";
myFrequentlyAccessedData = (object)cc;
Cache.Insert("key1", myFrequentlyAccessedData, null, System.Web.Caching.Cache.NoAbsoluteExpiration, TimeSpan.FromSeconds(30));
// 文件counter.xml内容有变动的话,Cache["key2"]即过期(换句话说,此原本Application生命周期的Cache将
// 从内存中被删除)
string inputvalue = "文件到期依赖";
object Mydata = (object)inputvalue;
System.Web.Caching.CacheItemRemovedCallback callback = new System.Web.Caching.CacheItemRemovedCallback(OnRemove);
Cache.Insert("key2", inputvalue, new System.Web.Caching.CacheDependency(Server.MapPath("counter.xml")), System.Web.Caching.Cache.NoAbsoluteExpiration, TimeSpan.Zero, System.Web.Caching.CacheItemPriority.Default, callback);
}
}
public static void OnRemove(string key, object cacheItem, System.Web.Caching.CacheItemRemovedReason reason)
{
reason1= "The cached value with key '" + key +"' was removed from the cache. Reason: " + reason.ToString();
}
protected void Button1_Click(object sender, EventArgs e)
{
if (Cache["key"] == null)
{
Response.Write("<br/>Cache[key]已过期");
}
else
{
Response.Write("<br/>"+Cache["key"].ToString());
}
if (Cache["key1"] == null)
{
Response.Write("<br/>Cache[key1]已过期");
}
else
{
Response.Write("<br/>" + Cache["key1"].ToString());
}
if (Cache["key2"] == null)
{
Response.Write("<br/>Cache[key2]已过期");
Response.Write(reason1);
}
else
{
Response.Write("<br/>" + Cache["key2"].ToString());
}
}
}
前台代码与给出来吧:
<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default2.aspx.cs" Inherits="Default2" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" >
<head runat="server">
<title>无标题页</title>
</head>
<body>
<form id="form1" runat="server">
<div>
<img src="counterimage.aspx" alt="nopic" /> <asp:Button ID="Button1" runat="server"
OnClick="Button1_Click" Text="Button" />
</div>
</form>
</body>
</html>
上面有一处有使用到CacheItemRemovedCallback这一对象,其实这是一个委托,具体,可以到参考:
另有
CacheItemRemovedReason枚举,该枚举和 CacheItemRemovedCallback 委托协同工作,以通知 ASP.NET 应用程序从 Cache 移除对象的时间和原因。
具体参考: