SqlDependancy 触发次数更多

SqlDependancy is firing more times

您好,我正在尝试使用 signalr 为新的数据库更改实施 sqldependancy。但问题是,如果我只编辑一行,那么 sqldependancy 也会触发更多时间。有一段时间它没有开火。我有没有 MVC 的 Web 应用程序。下面是我的代码

 public void page_load(object sender, EventArgs e)
        {
            //notification.GetAllUnreadSalesNotifications();
            NewScrapNotifications();

        }



        public void NewScrapNotifications()
        {


            string message = string.Empty;

            using (SqlConnection connection = new SqlConnection(IFTDAL.IFTCommon.DSN))
            {
                string query = "SELECT [Message] FROM [dbo].[DummyData]";

                using (SqlCommand command = new SqlCommand(query, connection))
                {
                    command.Notification = null;
                    SqlDependency dependency = new SqlDependency(command);
                    dependency.OnChange += new OnChangeEventHandler(dependency_OnChange);
                    connection.Open();
                    SqlDataReader reader = command.ExecuteReader();

                    if (reader.HasRows)
                    {
                        reader.Read();
                        message = reader[0].ToString();
                    }
                }
            }
        }



        private void dependency_OnChange(object sender, SqlNotificationEventArgs e)
        {

            if (e.Type == SqlNotificationType.Change)
            {
                IFTHub nHub = new IFTHub();
                nHub.NotfiyAllClients();
               // NewScrapNotifications();
                //LoadDashboardByDashboardViewID(1);
            }
        }

而且我在 Globa.asax

中也有下面的代码
 void Application_Start(object sender, EventArgs e)
            {
                // Code that runs on application startup
                RouteConfig.RegisterRoutes(RouteTable.Routes);
                BundleConfig.RegisterBundles(BundleTable.Bundles);
                SqlDependency.Start(DAL.DSN);

            }
            protected void Application_End(object sender, EventArgs e)
            {
                SqlDependency.Stop(DAL.DSN);
            }

您在每次页面加载(刷新)时创建新的 SQLDependency。我敢打赌,页面重新加载次数与通过 SignalR 接收的通知页面数量之间存在相关性。

每个应用生命周期只注册一次您的通知...