c# 缓存 Cache

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.Caching;

using System.Collections;
namespace CacheSample
{
    public partial class WebForm1 : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            ArrayList myarray = new ArrayList();//假设ArrayList的内容来自数据库

            myarray.Add("古代历史");

            myarray.Add("当代文学");

            myarray.Add("流行小说");

            myarray.Add("武侠小说");

            if (Cache["Categorys"] == null)  //判断是否存在缓存

            {

                //如果缓存不存在,则添加——保存时间是5秒

                Cache.Add("Categorys", myarray, null, DateTime.Now.AddSeconds(5),

                    TimeSpan.Zero, CacheItemPriority.Normal, null);

            }
        }

        protected void Button1_Click(object sender, EventArgs e)
        {
            if (Cache["Categorys"] != null)        //判断缓存是否失效

            {

                //如果没有失效,则取出缓存的列表,注意类型的转换。

                DropDownList1.DataSource = (ArrayList)Cache["Categorys"];

                DropDownList1.DataBind();

            }

            else

            {

                DropDownList1.Items.Clear();   //如果已经失效,则清空列表

            }
        }
    }
}

猜你喜欢

转载自www.cnblogs.com/leegj/p/10320308.html