当前位置:首页 > .NET内置对象之Cache对象

.NET内置对象之Cache对象

点击次数:1124  更新日期:2010-12-29
\n

Cache对象


\n

对于每个应用程序都需要创建该类的一个实例,并且只要对用的应用程序域保持活动,该实例便保持有效,有关此类实例的所有信息都需要通过HttpContext对象的Cache属性或Page对象的Cache属性来提供。


\n

新建一个网站,包括一个网页,代码如下:


\n

1、Default.aspx代码:


\n

<%@ Page Language=”C#” AutoEventWireup=”true” CodeFile=”Default.aspx.cs” Inherits=”_Default” %>


\n

<!DOCTYPE html PUBLIC “-//W3C//DTD XHTML 1.0 Transitional//EN” “http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd”>


\n

<html xmlns=”http://www.w3.org/1999/xhtml” >


\n

<head runat=”server”>


\n

<title>无标题页</title>


\n

<script runat=”server” language=”C#”>


\n

static bool itemRemoved = false;


\n

static CacheItemRemovedReason reason;


\n

CacheItemRemovedCallback onRemove = null;


\n

public void RemovedCallback(String k, Object v, CacheItemRemovedReason r)


\n

{


\n

itemRemoved = true;


\n

reason = r;


\n

}


\n

public void AddItemToCache(Object sender, EventArgs e)


\n

{


\n

itemRemoved = false;


\n

onRemove = new CacheItemRemovedCallback(this.RemovedCallback);


\n

if (Cache["Key1"] == null)


\n

Cache.Add(“Key1″, “Value1″, null, DateTime.Now.AddSeconds(60), TimeSpan.Zero, CacheItemPriority.High, onRemove);


\n

}


\n

public void RemoveItemFromCache(Object sender, EventArgs e)


\n

{


\n

if (Cache["Key1"] != null)


\n

Cache.Remove(“Key1″);


\n

}


\n

</script>


\n

</head>


\n

<body>


\n

<form id=”form1″ runat=”server”>


\n

<div>


\n

<input id=”Submit1″ type=”submit” onserverclick=”AddItemToCache” value=”Add Item To Cache” runat=”server” />


\n

<input id=”Submit2″ type=”submit” onserverclick=”RemoveItemFromCache” value=”Remove Item From Cache” runat=”server”/></div>


\n

</form>


\n

<%if (itemRemoved)


\n

{


\n

Response.Write(“RemovedCallback event raised.”);


\n

Response.Write(“<BR>”);


\n

Response.Write(“Reason:<B>” + reason.ToString() + “</B>”);


\n

}


\n

else


\n

{


\n

Response.Write(“Value of cache key:<B>” + Server.HtmlEncode(Cache["Key1"] as string) + “</B>”);


\n

}


\n

%>


\n

</body>


\n

</html>


\n

来源:csdn

\n