我有一個運行在MS SQL Server 2005和ASP.NET 3.5 Web應用程序上的數據庫。爲什麼我的SqlDependency沒有觸發
該數據庫包含一個產品目錄,我正在使用它將「頁面」提供到運行在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();
}
順便說一句,你應該總是在重新加載數據之前檢查SqlNotificationEventArg成員。否則,您有可能在生產環境中部署一個緊密的循環,重新加載每個錯誤的語句或錯誤的設置通知。最好是使緩存無效並讓下一個訪問加載數據,而不是主動重新加載通知(出於避免嚴重環路的不良情況的相同原因)。 – 2010-08-23 16:03:28