admin

SqlDependency onchange事件无限循环

sql

我有一个简单的查询,并且该事件在正确的时间触发。但是,一旦触发,.HasChangesSqlDependency对象的属性总是设置为true

第一次触发OnChange时,SqlNotificationEventArgs Info属性为“ Inserted”。第二次触发该事件是“已更改”。

  • 我在OnChange事件中注释了我所有的代码,以验证我的代码没有引起更改。
  • 数据库中已启用Servicebroker

以下代码是否有原因导致onChange事件无限循环?

static void Main()
{
    SqlDependency.Stop(Properties.Settings.Default.DEVConnectionString);
    SqlDependency.Start(Properties.Settings.Default.DEVConnectionString);

    using (SqlConnection cn = new SqlConnection(Properties.Settings.Default.DEVConnectionString))
    {
        cn.Open();

        using (SqlCommand cmd = new SqlCommand("SELECT UserPageActionLogID, PageActionID FROM dbo.UserPageActionLog WHERE PageActionID != 3 ORDER BY UserPageActionLogID ASC", cn))
        {
            cmd.Notification = null;

            SqlDependency dep = new SqlDependency(cmd);
            dep.OnChange += dep_onchange;

            using (SqlDataReader dr = cmd.ExecuteReader())
            {
                while (dr.Read())
                {
                    //Do nothing on first run
                }
            }
        }
    }
    Application.Run(); //Prevents the application from closing
}

private static void dep_onchange(object sender, SqlNotificationEventArgs e)
{
    SqlDependency dependency = sender as SqlDependency;
    dependency.OnChange -= dep_onchange;

    //Do stuff for the function. I commented this out and still had an issue

    //Resubscribe to the event to continue catching future changes
    dependency.OnChange += dep_onchange;
}

阅读 183

收藏
2021-06-07

共1个答案

admin

看来OnChange处理程序和SqlDependency实例都只适合一个事件。触发事件并取消订阅处理程序后,需要将处理程序注册到新的SqlDependency对象。

请参阅此处的链接以获取完整详细信息:http : //msdn.microsoft.com/zh-
cn/library/a52dhwx7(v=vs.80).aspx

2021-06-07