Cache示例

public partial class Cache : System.Web.UI.Page
{
    //cache是否有效
    static bool itemRemoved = false;

    //Cache无效原因
    static CacheItemRemovedReason reason;

    //Cache失效时通知应用程序的回调方法
    CacheItemRemovedCallback onRemove = null;

    /// <summary>
    /// 定义回调方法
    /// </summary>
    /// <param name="k"></param>
    /// <param name="v"></param>
    /// <param name="r"></param>
    public void RemovedCallback(String k, Object v, CacheItemRemovedReason r){
        itemRemoved = true;
        reason = r;      

    }


   
    protected void Page_Load(object sender, EventArgs e)
    {
       
       
       
    }

    /// <summary>
    /// 写Cache
    /// </summary>
    /// <param name="sender"></param>
    /// <param name="e"></param>
    protected void btAdd_Click(object sender, EventArgs e)
    {
        //设置Cache有效
        itemRemoved = false;

       
        onRemove = new CacheItemRemovedCallback(this.RemovedCallback);

        //添加Cache数据

        //
        //if (Cache["Key1"] == null)
        //    Cache.Add("Key1", "Value 1", null, DateTime.Now.AddSeconds(60), TimeSpan.Zero, CacheItemPriority.High, onRemove);

        //十分钟过期,null的位置为依赖项
        if (Cache["Key1"] == null)
            Cache.Add("Key1", "Value 1",null, DateTime.Now.AddSeconds(10), System.Web.Caching.Cache.NoSlidingExpiration, CacheItemPriority.High, onRemove);

        Response.Write(Cache["Key1"].ToString());  
  

    }

    /// <summary>
    /// 移除Cache
    /// </summary>
    /// <param name="sender"></param>
    /// <param name="e"></param>
    protected void btDel_Click(object sender, EventArgs e)
    {
        if (Cache["Key1"] != null)
            Cache.Remove("Key1");

        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>");
        }

    }

posted @ 2006-11-22 15:27  疯一样的自由  阅读(615)  评论(0编辑  收藏  举报