缓存失效的三种方式

-----------------------WebFrom1.aspx---------------------------------

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title></title>
</head>
<body>
    <form id="form1" runat="server">
    <div>
        <asp:GridView ID="GridView1" runat="server">
        </asp:GridView>
    </div>
    </form>
</body>
</html>

----------------------------WebFrom1.aspx.cs----------------------------------------

protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                if (Cache["news"] == null)
                {
                    DataTable dt = LoadData();
                    //将缓存和外部文件关联,外部文件以改变,缓存立即失效
                    //Cache.Insert("news", dt, new CacheDependency(@"d:\cache.txt"));

                    //为缓存设定一个绝对时间,让缓存在这个时间到的时候失效
                    //Cache.Insert("news", dt, null, DateTime.Now.AddSeconds(20), TimeSpan.Zero);

                   //为缓存设置一个相对时间,让缓存在这个时间到的时候失效
                    Cache.Insert("news", dt, null, DateTime.MaxValue, TimeSpan.FromSeconds(30));


                   //简单的设置一个缓存
                    Cache.Insert("news", dt);
                    this.GridView1.DataSource = dt;
                    this.GridView1.DataBind();
                }
                else
                {
                    DataTable dt = Cache["news"] as DataTable;
                    this.GridView1.DataSource = dt;
                    this.GridView1.DataBind();
                }
            }
        }
        private DataTable LoadData()
        {
            string strcon = ConfigurationManager.ConnectionStrings["Sqlserver"].ConnectionString;
            SqlConnection conn = new SqlConnection(strcon);
            SqlCommand cmd = conn.CreateCommand();
            cmd.CommandText = "pro_FenYe";
            cmd.CommandType = CommandType.StoredProcedure;
            cmd.Parameters.AddWithValue("@pagesize",500);
            cmd.Parameters.AddWithValue("@pageindex",1);
            DataTable dt = new DataTable();
            SqlDataAdapter adapter = new SqlDataAdapter(cmd);
            adapter.Fill(dt);
            cmd.Dispose();
            conn.Dispose();
            return dt;
        }
    }

----------------------------web.config----------------------------------

  <system.web>
        <compilation debug="true" targetFramework="4.0" />
      <caching>
        <sqlCacheDependency pollTime="500">
          <databases>
            <add name="sqldependency" connectionStringName="Sqlserver"/>
          </databases>
        </sqlCacheDependency>
      </caching>
    </system.web>


在规定时间内访问一个网页时,网页上的内容暂时保持不变,过了特定时间,网页上的内容就会重新访问服务器获取数据。

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值