我尝试设置 SQL 依赖项以触发“计数行”查询(用 C#、SQL Server 2008 Express 编写),但在原始订阅 SQLNotificationType 消失后,事件处理程序似乎再也不想触发(尽管行正在添加,我已经检查了 SQL,它正在返回预期值......)。
我的代码如下。任何想法都非常感谢!
编辑:此代码所在的项目是 WPF 程序。我将此特定代码存储在一个单独的类中,我的 WPF 程序在“初始化”事件处理程序中创建了一个实例。然后我在这个类中有一个方法,它基本上首先调用 ConnectToDatabase(),然后调用 SetupSQLDependency()。
编辑 2:作为旁注,这个程序是一个 WPF,我希望将它分发给一些用户。目标是每当将新行添加到数据库时,使用特定信息更新 WPF。我认为这将是最好的方法,而不是总是查询数据库。
private void ConnectToDatabase()
{
//This method is the first to be called, and is the entry
// point into my SQL database code.
databaseConnection = new SqlConnection(connectionString);
// Setup command used in SqlDependecy
SqlCommand tempCmd = new SqlCommand();
tempCmd.Connection = databaseConnection;
tempCmd.CommandText = "SELECT COUNT(ID) FROM [Example].[dbo].[ExampleTable]";
sqlCmd = tempCmd;
try
{ databaseConnection.Open(); }
catch (Exception e)
{ writeDebug(e.ToString()); }
}
private void SetupSQLDependency()
{
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
if (e.Type == SqlNotificationType.Change)
{
//++++++ THIS IS THE BLOCK THAT IS NEVER TRIGGERED ++++++//
// Have to remove this as it only work's once
SqlDependency sqlDep = sender as SqlDependency;
sqlDep.OnChange -= sqlDep_OnChange;
// Resetup Dependecy
SetupSQLDependency();
}
else if (e.Type == SqlNotificationType.Subscribe)
{
double te = 12; // Used this just to test a break... code is useless
}
}