我一直在尝试让SqlCacheDependency正常工作。我认为我已经正确设置了所有内容,但是当我更新表时,缓存中的项目不会失效。
你能查看我的代码,看看我是否遗漏了什么?
我启用了Sandbox数据库的Service Broker。 我已将以下代码放在Global.asax文件中。我还重新启动IIS以确保它被调用。
void Application_Start(object sender, EventArgs e) {
SqlDependency.Start(ConfigurationManager.ConnectionStrings["SandboxConnectionString"].ConnectionString);
}
我已将此条目放在web.config文件中:
<system.web>
<caching>
<sqlCacheDependency enabled="true" pollTime="10000">
<databases>
<add name="Sandbox" connectionStringName="SandboxConnectionString"/>
</databases>
</sqlCacheDependency>
</caching>
</system.web>
我调用此代码将项目放入缓存中:
protected void CacheDataSetButton_Click(object sender, EventArgs e) {
using (SqlConnection sqlConnection = new SqlConnection(ConfigurationManager.ConnectionStrings["SandboxConnectionString"].ConnectionString)) {
using (SqlCommand sqlCommand = new SqlCommand("SELECT PetID, Name, Breed, Age, Sex, Fixed, Microchipped FROM dbo.Pets", sqlConnection)) {
using (SqlDataAdapter sqlDataAdapter = new SqlDataAdapter(sqlCommand)) {
DataSet petsDataSet = new DataSet();
sqlDataAdapter.Fill(petsDataSet, "Pets");
SqlCacheDependency petsSqlCacheDependency = new SqlCacheDependency(sqlCommand);
Cache.Insert("Pets", petsDataSet, petsSqlCacheDependency, DateTime.Now.AddSeconds(10), Cache.NoSlidingExpiration);
}
}
}
}
然后我用这段代码绑定GridView:
protected void BindGridViewButton_Click(object sender, EventArgs e) {
if (Cache["Pets"] != null) {
GridView1.DataSource = Cache["Pets"] as DataSet;
GridView1.DataBind();
}
}
在尝试DataBind GridView之间,我更改表的值,期望它使Cache [“Pets”]项无效,但它似乎无限期地保留在Cache中。
答案 0 :(得分:1)
在执行命令之前,必须将SqlCacheDependency附加到SqlCommand :
using (SqlDataAdapter sqlDataAdapter = new SqlDataAdapter(sqlCommand)) {
DataSet petsDataSet = new DataSet();
SqlCacheDependency petsSqlCacheDependency =
new SqlCacheDependency(sqlCommand);
sqlDataAdapter.Fill(petsDataSet, "Pets");
Cache.Insert("Pets", petsDataSet, petsSqlCacheDependency,
DateTime.Now.AddSeconds(10), Cache.NoSlidingExpiration);
}