我试图弄清楚如何使用 SQL Dependency (C# 4.0) 来“监听”对数据库的更改。我在网上看到了很多东西,但它们似乎是(自然地)为使用依赖关系来提取 SQL 依赖关系所依赖的相同数据而定制的。比如这篇文章。
我想要做的是创建一个依赖项,当它被触发时,会导致许多不同的 SQL“选择”查询(我可以将其存储在其他方法等中)。例如:我正在尝试设置一个监视表中行数的依赖项。当行数增加时,执行 x, y, z(即我的程序不关心行数是多少,只关心它增加了,什么时候做一堆事情)。
有什么想法是最好的方法吗?
编辑:我已经附上了我目前拥有的代码。我试图弄清楚如何将 SqlDependency 的设置与 GetData() 进程分开。但目前,我认为我进入了一个无限循环,因为在我删除事件处理程序并重新运行“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();
}