【发布时间】:2014-02-02 15:01:49
【问题描述】:
据我了解,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]);
【问题讨论】:
-
您在错误的队列中查找。
command.Notification为 null,因此它使用默认队列名称。 See VB example here
标签: c# sql wpf sqldependency