.NET内置对象之Cache对象_[Asp.Net教程]
Cache对象
对于每个应用程序都需要创建该类的一个实例,并且只要对用的应用程序域保持活动,该实例便保持有效,有关此类实例的所有信息都需要通过HttpContext对象的Cache属性或Page对象的Cache属性来提供。
新建一个网站,包括一个网页,代码如下:
1、Default.aspx代码:
<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits="_Default" %>
无标题页
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");
}
<%if (itemRemoved)
{
Response.Write("RemovedCallback event raised.");
Response.Write("
");
Response.Write("Reason:" + reason.ToString() + "");
}
else
{
Response.Write("Value of cache key:" + Server.HtmlEncode(Cache["Key1"] as string) + "");
}
%>
来源:csdn