2010-08-23 106 views
3

我有一個運行在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(); 
} 
+2

順便說一句,你應該總是在重新加載數據之前檢查SqlNotificationEventArg成員。否則,您有可能在生產環境中部署一個緊密的循環,重新加載每個錯誤的語句或錯誤的設置通知。最好是使緩存無效並讓下一個訪問加載數據,而不是主動重新加載通知(出於避免嚴重環路的不良情況的相同原因)。 – 2010-08-23 16:03:28

回答

11

檢查數據庫sys.transmission_queue。您的通知很可能會在那裏,因爲無法遞送而保留。 transmission_status將解釋爲什麼會發生這種情況。有關更詳細的故障排除指南,請參閱Troubleshooting Dialogs

最通常的問題是由於EXECUTE AS並不是被孤立的數據庫DBO所有權滿足和基礎設施的要求,可通過以下方式解決:

ALTER AUTHORIZATION ON DATABASE::<dbname> TO [sa]; 

然而,該解決方案從案例依賴到的情況下,根據實際問題,如上所述。

+0

你可以看看我的問題。我不知道爲什麼它不工作: https://stackoverflow.com/questions/46434652/sqldependency-not-firing – 2017-09-26 21:34:11

相關問題