Effect: When you access a webpage within the specified time, the content on the webpage remains unchanged. When the time passes, the content on the webpage will access the server again to obtain data.
Front-end:
<% @ Page Language = "C #" AutoEventWireup = "true" CodeBehind = "WebForm1.aspx. cs" Inherits = "cache. WebForm1" %>
<! DOCTYPE html PUBLIC "-// W3C // dtd xhtml 1.0 Transitional // EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<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>
Background:
Protected void Page_Load (object sender, EventArgs e)
{
If (! IsPostBack)
{
If (Cache ["news"] = null)
{
DataTable dt = LoadData ();
// Associate the cache with an external file. If the external file is changed, the cache immediately becomes invalid.
// Cache. Insert ("news", dt, new CacheDependency (@ "d: \ cache.txt "));
// Set an absolute time for the cache so that the cache will expire at this time
// Cache. Insert ("news", dt, null, DateTime. Now. AddSeconds (20), TimeSpan. Zero );
// Set a relative time for the cache to invalidate the cache at this time.
Cache. Insert ("news", dt, null, DateTime. MaxValue, TimeSpan. FromSeconds (30 ));
// Set a cache
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;
}
}
Code for setting the time in 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>