根据您的 SQL 数据库版本,您可以使用 SqlCacheDependency。
在您的 web.config 中非常简短
<caching>
<sqlCacheDependency pollTime="10000" enabled="true" >
<databases>
<add connectionStringName="ConnectionString" name="Coverage"/>
</databases>
</sqlCacheDependency>
</caching>
然后在代码中
private void BindData()
{
// if null then fetch from the database
if (Cache["CoverageDataTable"] == null)
{
// Create the cache dependency
SqlCacheDependency dep = new SqlCacheDependency("Coverage", CoverageDataTable");
string connectionString = ConfigurationManager.ConnectionStrings[
"ConnectionString"].ConnectionString;
SqlConnection myConnection = new SqlConnection(connectionString);
SqlDataAdapter ad = new SqlDataAdapter("SELECT ColA, ColB, ColC " +
"FROM CoverageDataTable", myConnection);
DataSet ds = new DataSet();
ad.Fill(ds);
// put in the cache object
Cache.Insert("CoverageDataTable", ds, dep);
}
gvCoverageDataTable.DataSource = Cache["CoverageDataTable"] as DataSet;
gvCoverageDataTable.DataBind();
}
一些背景可以在这里找到:在 ASP.NET 中使用 SqlCacheDependency 类进行缓存