效果當(dāng)在規(guī)定時(shí)間內(nèi)訪問一個(gè)網(wǎng)頁時(shí),網(wǎng)頁上的內(nèi)容咱是保持不變,時(shí)間一過,網(wǎng)頁上的內(nèi)容就會(huì)重新訪問服務(wù)器,獲取數(shù)據(jù)托福答案
前臺(tái):
<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="WebForm1.aspx.cs" Inherits="緩存.WebForm1" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" ".w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns=".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>
后臺(tái):
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
if (Cache["news"] == null)
{
DataTable dt = LoadData();
//將緩存和外部文件關(guān)聯(lián),外部文件以改變,緩存立即失效
//Cache.Insert("news", dt, new CacheDependency(@"d:\cache.txt"));
//為緩存設(shè)定一個(gè)絕對(duì)時(shí)間,讓緩存在這個(gè)時(shí)間到的時(shí)候失效
//Cache.Insert("news", dt, null, DateTime.Now.AddSeconds(20), TimeSpan.Zero);
//為緩存設(shè)置一個(gè)相對(duì)時(shí)間,讓緩存在這個(gè)時(shí)間到的時(shí)候失效
Cache.Insert("news", dt, null, DateTime.MaxValue, TimeSpan.FromSeconds(30));
//簡(jiǎn)單的設(shè)置一個(gè)緩存
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中的設(shè)置時(shí)間的代碼:
<system.web>
<compilation debug="true" targetFramework="4.0" />
<caching>
<sqlCacheDependency pollTime="500">
<databases>
<add name="sqldependency" connectionStringName="Sqlserver"/>
</databases>
</sqlCacheDependency>
</caching>
</system.web>