2012-01-24 67 views
4

我想弄清楚如何使用SQL依賴關係(C#4.0)來偵聽對數據庫的更改。我在網上看到了很多東西,但是他們似乎是自然而然地使用依賴關係來提取SQL依賴關係所依賴的相同數據。例如,this article在C#中的SQL依賴關係

我想要做的是創建一個依賴關係,當觸發時,會導致大量不同的SQL Select(查詢可以存儲在其他方法等)查詢。例如:我試圖設置一個依賴項來監視表中的行數。當行數增加時,則執行x,y,z(即我的程序不關心行數是多少,只是它增加了,什麼時候它做了很多事情)。

有什麼想法是最好的方法來做到這一點?

編輯:我已經附上我的代碼,因爲我有它目前。我想弄清楚如何從GetData()過程中分離設置SqlDependency。目前,雖然,我覺得我走進了一下一個無限循環的作爲後,我刪除了事件處理程序,然後重新運行「SetupSqlDependency()」,它會馬上回來到這個事件處理

private void SetupSQLDependency() 
    { 
     // Tutorial for this found at: 
     // http://www.dreamincode.net/forums/topic/156991-using-sqldependency-to-monitor-sql-database-changes/ 

     SqlDependency.Stop(connectionString); 
     SqlDependency.Start(connectionString); 

     sqlCmd.Notification = null; 

     // create new dependency for SqlCommand 
     SqlDependency sqlDep = new SqlDependency(sqlCmd); 
     sqlDep.OnChange += new OnChangeEventHandler(sqlDep_OnChange); 

     SqlDataReader reader = sqlCmd.ExecuteReader(); 
    } 
private void sqlDep_OnChange(object sender, SqlNotificationEventArgs e) 
    { 
     // FROM: http://msdn.microsoft.com/en-us/a52dhwx7.aspx 

     #region 
     // This event will occur on a thread pool thread. 
     // Updating the UI from a worker thread is not permitted. 
     // The following code checks to see if it is safe to 
     // update the UI. 

     /* ISynchronizeInvoke i = (ISynchronizeInvoke)this; 

     // If InvokeRequired returns True, the code 
     // is executing on a worker thread. 
     if (i.InvokeRequired) 
     { 
      // Create a delegate to perform the thread switch. 
      OnChangeEventHandler tempDelegate = new OnChangeEventHandler(sqlDep_OnChange); 

      object[] args = { sender, e }; 

      // Marshal the data from the worker thread 
      // to the UI thread. 
      i.BeginInvoke(tempDelegate, args); 

      return; 
     }*/ 
     #endregion 

     // Have to remove this as it only work's once 
     SqlDependency sqlDep = sender as SqlDependency; 
     sqlDep.OnChange -= sqlDep_OnChange; 

     // At this point, the code is executing on the 
     // UI thread, so it is safe to update the UI.. 

     // 1) Resetup Dependecy 
     SetupSQLDependency(); 

    } 

回答

5

你可以連接起來的SqlDependency 。改變事件並在這個事件處理器中做任何你喜歡的事情。事實上,這是做你想做的事情的唯一方法,它沒有任何問題。

在僞代碼看起來是這樣的:

var dep = new SqlDependency(GetSqlQueryForMonitoring()); 
dep.Change +=() => { 
var data = ExecSql(GetDataQuerySql()); 
UpdateCache(data); 
}; 

很簡單。只需使用兩個不同的查詢。

編輯:在您的示例代碼中有一條評論說您正在UI線程上運行。爲什麼會這樣呢?我對此表示懷疑。無論如何,在重新設置依賴關係之前,您應該運行查詢,否則您可能會發生併發失效事件。

我建議你從數據庫中獲取新鮮的數據,然後發送消息給UI來更新它(調用)。

+0

我想我很困惑的是,他們將設置依賴關係的過程與「GetData」材質結合在一起。我試圖找出如何分開它,如果它需要 – keynesiancross

+0

編輯闡述你的觀點。 – usr

+1

謝謝 - 儘管您在哪裏獲得.Change事件?我只獲得OnChange事件? (或者我設法跨越語言...)。我已經更新了我的問題以包含我的當前代碼 – keynesiancross