Cache对象
对于每个应用程序都需要创建该类的一个实例,并且只要对用的应用程序域保持活动,该实例便保持有效,有关此类实例的所有信息都需要通过HttpContext对象的Cache属性或Page对象的Cache属性来提供。
新建一个网站,包括一个网页,代码如下:
1、Default.aspx代码:
<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits="_Default" %>
<!DOCTYPE html PUBLIC "-//W 3C //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>
<script runat="server" language="C#">
static bool itemRemoved = false;
static CacheItemRemovedReason reason;
CacheItemRemovedCallback onRemove = null;
public void RemovedCallback(String k, Object v, CacheItemRemovedReason r)
{
itemRemoved = true;
reason = r;
}
public void AddItemToCache(Object sender, EventArgs e)
{
itemRemoved = false;
onRemove = new CacheItemRemovedCallback(this.RemovedCallback);
if (Cache["Key1"] == null)
Cache.Add("Key1", "Value1", null, DateTime.Now.AddSeconds(60), TimeSpan.Zero, CacheItemPriority.High, onRemove);
}
public void RemoveItemFromCache(Object sender, EventArgs e)
{
if (Cache["Key1"] != null)
Cache.Remove("Key1");
}
</script>
</head>
<body>
<form id="form1" runat="server">
<div>
<input id="Submit1" type="submit" onserverclick="AddItemToCache" value="Add Item To Cache" runat="server" />
<input id="Submit2" type="submit" onserverclick="RemoveItemFromCache" value="Remove Item From Cache" runat="server"/></div>
</form>
<%if (itemRemoved)
{
Response.Write("RemovedCallback event raised.");
Response.Write("<BR>");
Response.Write("Reason:<B>" + reason.ToString() + "</B>");
}
else
{
Response.Write("Value of cache key:<B>" + Server.HtmlEncode(Cache["Key1"] as string) + "</B>");
}
%>
</body>
</html>