SQL依赖关系OnChange事件在页面刷新原因上多次调用

Usm*_*man 2 c# sql-server

任何机构都可以告诉我在页面刷新后多次SQL依赖OnChange事件调用背后的原因是什么.这背后可能的原因是什么?在页面刷新之前,数据库中每次更改只调用一次.

Usm*_*man 6

问题:每次创建新的SQL Dependency变量时刷新页面,以及与该新的依赖变量关联的新的Change_Event_Handler,并且当调用SQL依赖项时,它必须取消订阅所有现有的更改事件,这些事件会多次调用我的功能.

解决方案:在类中将这两个变量定义为static:

    internal static SqlCommand command = null;
    internal static SqlDependency dependency = null;
Run Code Online (Sandbox Code Playgroud)

然后使用这样的函数,并在应用程序启动时首先停止依赖,然后再次启动,然后执行其他类似的操作.检查依赖项是否已经启动然后不创建新的依赖关系连接和类似的新ChangeEvent,

    using (EmailController.command = new SqlCommand(SQL.emailmessagesbyaccount_sql(), conn.getDbConnection()))
    {
        defaultemailid = emailid;
        EmailController.command.Parameters.Add(new SqlParameter("@emailaccountid", emailid));

        EmailController.command.Notification = null;

        if (EmailController.dependency == null)
        {
            EmailController.dependency = new SqlDependency(EmailController.command);
            EmailController.dependency.OnChange += new OnChangeEventHandler(emailMessages_OnChange);
        }
        var reader = EmailController.command.ExecuteReader();
    }
Run Code Online (Sandbox Code Playgroud)

最后你必须像这样实现onchange_event:

private void emailMessages_OnChange(object sender, SqlNotificationEventArgs e)
{
    if (e.Type == SqlNotificationType.Change)
    {
        //if not null then unsubscribe the calling event
        if (EmailController.dependency != null)
        {
            EmailController.dependency.OnChange -= emailMessages_OnChange;
        }
        //do my email updates
        NotificationHub.EmailUpdateRecords();


        // here again subscribe for the new event call re initialize the
        // exising dependecy variable the one which we defined as static

        SingletonDbConnect conn = SingletonDbConnect.getDbInstance();
        using (EmailController.command = new SqlCommand(SQL.emailmessagesbyaccount_sql(), conn.getDbConnection()))
        {
            EmailController.command.Parameters.Add(new SqlParameter("@emailaccountid", defaultemailid));
            EmailController.command.Notification = null;

            EmailController.dependency = new SqlDependency(EmailController.command);
            EmailController.dependency.OnChange += new OnChangeEventHandler(emailMessages_OnChange);

            var reader = EmailController.command.ExecuteReader();

        }

    }
}
Run Code Online (Sandbox Code Playgroud)

实际上这是我的代码逻辑,但希望你能从这个实现中得到很好的想法如何处理这种问题让我磕磕绊绊了一个星期.