繁体   English   中英

SqlDependency.OnChange 继续触发

[英]SqlDependency.OnChange keep firing

据我了解,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]);

今天我遇到了完全相同的问题,对我来说问题与设置选项有关,请注意,您可以通过在DependencyOnChange事件处理程序中放置断点并查看SqlNotificationEventArgs信息属性来查看错误是什么(有关更多详细信息,请参见此处

注册查询通知的查询需要进行订阅的数据库连接启用正确的 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(有关更多详细信息,请参见此处)。

另外,如果要启用服务代理(Northwind 是数据库名称),请考虑以下步骤

ALTER DATABASE Northwind SET enable_broker WITH ROLLBACK IMMEDIATE
ALTER DATABASE Northwind SET TRUSTWORTHY ON
ALTER AUTHORIZATION ON DATABASE::Northwind TO [sa]

其他需要考虑的事情会导致 SqlDependency 持续触发:

  1. 使用不特定的查询(即没有通配符“*”或 DISTINCT 用法)。

  2. 不使用完全限定的表名(例如:SELECT Person FROM PersonTable 与 SELECT Person FROM dbo .PersonTable)。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM