我想弄清楚如何使用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();
}
我想我很困惑的是,他們將設置依賴關係的過程與「GetData」材質結合在一起。我試圖找出如何分開它,如果它需要 – keynesiancross
編輯闡述你的觀點。 – usr
謝謝 - 儘管您在哪裏獲得.Change事件?我只獲得OnChange事件? (或者我設法跨越語言...)。我已經更新了我的問題以包含我的當前代碼 – keynesiancross