我有一个在 MS SQL Server 2005 上运行的数据库和一个 ASP.NET 3.5 Web 应用程序。
该数据库包含一个产品目录,我用它来将“页面”提供给在 Web 应用程序中运行的 CMS。创建页面后,应用程序会将它们缓存起来,因此我需要将此更改通知应用程序,以便它可以重新创建页面对象。
CMS 使用它自己的缓存,因此不能使用 SqlCacheDependency 来执行此任务。
当我启动应用程序时,我确实让订阅者出现在结果中
select * from sys.dm_qn_subscriptions
但是,只要我向表中添加一些数据,订阅者就会消失,并且 OnChanged 事件永远不会触发。
在我的启动代码中,我有以下内容
// Ensure the database is setup for notifications
SqlCacheDependencyAdmin.EnableNotifications(DataHelper.ConnectionString);
SqlCacheDependencyAdmin.EnableTableForNotifications(DataHelper.ConnectionString, "Category");
SqlCacheDependencyAdmin.EnableTableForNotifications(DataHelper.ConnectionString, "Product");
if (!SqlDependency.Start(DataHelper.ConnectionString, SqlDependencyQueueName))
throw new Exception("Something went wrong");
string queueOptions = string.Format("service = {0}", SqlDependencyQueueName);
using (var connection = new SqlConnection(DataHelper.ConnectionString))
{
connection.Open();
using (SqlCommand command = new SqlCommand(@"SELECT [CategoryID],[Name]
FROM [dbo].[Category]", connection))
{
// Create a dependency and associate it with the SqlCommand.
dependency = new SqlDependency(command, queueOptions, 0);
// Subscribe to the SqlDependency event.
dependency.OnChange += new OnChangeEventHandler(OnDependencyChange);
command.ExecuteReader().Close();
}
}
// ...
void OnDependencyChange(object sender, SqlNotificationEventArgs e)
{
Debugger.Break(); // This never hits
this.ReloadData();
}