根据我的理解,SqlDependency.OnChange只应在查询结果发生变化时触发 这是一个小应用程序,我在事件中放置了一个计数器,并显示它,它似乎连续点火,即使我没有添加新行,我尝试了一些博客的一些例子,我得到相同的结果,我是什么做错了? 我检查了“sys.transmission_queue”和“sys.dm_qn_subscriptions”都是空的 SqlNotificationEventArgs属性值为“Info = Invalid,Source = Statement,Type = Subscribe”
private void Runnn()
{
var query = from x in Entities.Contacts select x;
qqq.ItemsSource = query.ToList();
con = new SqlConnection(@"server=PC\sqlexpress08;database=test2db;Trusted_Connection=yes;");
command = new SqlCommand("SELECT ID,Name FROM dbo.Contacts",con);
BeginSqlDependency(con.ConnectionString);
}
private void BeginSqlDependency(string connection)
{
SqlDependency.Stop(connection);
SqlDependency.Start(connection);
RegisterSqlDependency();
}
private void RegisterSqlDependency()
{
command.Notification = null;
dependency = new SqlDependency(command);
dependency.OnChange += new OnChangeEventHandler(DependencyOnChange);
RegisterSqlCommand();
}
private void RegisterSqlCommand()
{
con.Open();
command.ExecuteNonQuery();
con.Close();
}
private void DependencyOnChange(object sender, SqlNotificationEventArgs e)
{
SqlDependency dependency = (SqlDependency)sender;
dependency.OnChange -= DependencyOnChange;
var query = from x in Entities.Contacts select x;
Application.Current.Dispatcher.BeginInvoke(DispatcherPriority.Background, new Action(() => { qqq.ItemsSource = null; qqq.ItemsSource = query.ToList(); ee.Text = i.ToString(); }));
RegisterSqlDependency();
i++;
}
##SQL server Express SP2 2008##
ALTER DATABASE test2db SET ENABLE_BROKER;
CREATE QUEUE ContactChangeMessages;
CREATE SERVICE ContactChangeNotifications
ON QUEUE ContactChangeMessages
([http://schemas.microsoft.com/SQL/Notifications/PostQueryNotification]);
答案 0 :(得分:1)
今天我遇到了完全相同的问题,对我而言,问题与设置选项有关,请注意您可以通过在 DependencyOnChange 事件处理程序中设置断点并查看错误来查看错误是什么 SqlNotificationEventArgs 信息属性(有关详细信息,请参阅here)
为Query Notification注册查询需要在其上进行订阅的数据库连接才能启用正确的SET OPTIONS:
ANSI_NULLS ON
ANSI_PADDING ON
ANSI_WARNINGS ON
CONCAT_NULL_YIELDS_NULL ON
QUOTED_IDENTIFIER ON
NUMERIC_ROUNDABORT OFF
ARITHABORT ON
并在Sql Studio Management的数据库属性对话框中打开ARITHABORT(有关详细信息,请参阅here)。
另外,如果要启用服务代理(Northwind是数据库名称)
,请考虑以下步骤ALTER DATABASE Northwind SET enable_broker WITH ROLLBACK IMMEDIATE
ALTER DATABASE Northwind SET TRUSTWORTHY ON
ALTER AUTHORIZATION ON DATABASE::Northwind TO [sa]
答案 1 :(得分:1)
其他需要考虑的会导致 SqlDependency 持续触发的事情:
使用不具体的查询(即没有通配符“*”或 DISTINCT 用法)。
未使用完全限定的表名(例如:SELECT Person FROM PersonTable 与 SELECT Person FROM dbo.PersonTable)。