SqlDependency在Windows窗体应用程序中速度很快,但在ASP.net MVC应用程序中却很慢

本文关键字:应用程序 net ASP MVC 但在 很快 Windows 窗体 速度 SqlDependency | 更新日期: 2023-09-27 17:59:10

我编写了一个windows窗体应用程序(C#),它使用SqlDependency来检测更改[From HERE]。它运行良好,对用户表的任何更改都会立即触发dep_onchange事件。

我在ASP.net MVC应用程序中使用了完全相同的代码,并编写了以下代码来测试它

1-如果我刷新test.cshtml页面,有时dep_onchange事件会延迟触发,甚至更糟的是,它根本不会触发。

2-如果我在SQL Server Management Studio中的"Users"表中添加或删除一行,它会触发windows窗体应用程序的dep_onchange事件,但从不触发ASP.net应用程序的dep_onchange。

  public ActionResult Test()
        {
            string connectionString = @"Data Source=MSSQLSERVER2014;Initial Catalog=MyDatabase; user ID=sa; password=1234";
            try
            {
                using (SqlConnection cn = new SqlConnection(connectionString))
                {
                    using (SqlCommand cmd = cn.CreateCommand())
                    {
                        cmd.CommandText = "INSERT INTO Users VALUES (@FirstName, @LastName)";
                        cmd.CommandType = CommandType.Text;
                        cmd.Parameters.AddWithValue("@FirstName", "farid");
                        cmd.Parameters.AddWithValue("@LastName", "Artina");
                        cn.Open();
                        cmd.ExecuteNonQuery();
                    }
                }
            }
            catch (Exception exception)
            {
            }

            return View();
        }

Global.asax.cs代码:

 protected void Application_Start()
        {
            AreaRegistration.RegisterAllAreas();
            FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
            RouteConfig.RegisterRoutes(RouteTable.Routes);
            BundleConfig.RegisterBundles(BundleTable.Bundles);
            GetNames();
        }

        protected void Application_End()
        {
            //Stop SQL dependency
             SqlDependency.Stop(connectionString);
        }

 private void GetNames()
        {
            try
            {
                if (!DoesUserHavePermission())
                    return;

                SqlDependency.Stop(connectionString);
                SqlDependency.Start(connectionString);
                using (SqlConnection cn = new SqlConnection(connectionString))
                {
                    using (SqlCommand cmd = cn.CreateCommand())
                    {
                        cmd.CommandType = CommandType.Text;
                        cmd.CommandText = "SELECT FirstName, LastName FROM dbo.[Users]";
                        cmd.Notification = null;
                        //  creates a new dependency for the SqlCommand
                        SqlDependency dep = new SqlDependency(cmd);
                        //  creates an event handler for the notification of data
                        //      changes in the database.
                        //  NOTE: the following code uses the normal .Net capitalization methods, though
                        //      the forum software seems to change it to lowercase letters
                        dep.OnChange += new OnChangeEventHandler(dep_onchange);
                        cn.Open();
                        List<String> Items = new List<string>();
                        using (SqlDataReader dr = cmd.ExecuteReader())
                        {
                            while (dr.Read())
                            {
                                Items.Add(dr.GetString(0) + " " + dr.GetString(1));
                            }
                        }
                    }
                }
            }
            catch (Exception exception)
            {
                throw new Exception(exception.Message);
            }
        }

        private bool DoesUserHavePermission()
        {
            try
            {
                SqlClientPermission clientPermission = new SqlClientPermission(PermissionState.Unrestricted);
                // will throw an error if user does not have permissions
                clientPermission.Demand();
                return true;
            }
            catch
            {
                return false;
            }
        }

        void dep_onchange(object sender, SqlNotificationEventArgs e)
        {
            GetNames();
            SqlDependency dep = sender as SqlDependency;
            dep.OnChange -= new OnChangeEventHandler(dep_onchange);
        }

如有任何帮助,我们将不胜感激。

SqlDependency在Windows窗体应用程序中速度很快,但在ASP.net MVC应用程序中却很慢

connectionString中,使用FQDN或Windows命名,将MSSQLSERVER2014替换为(例如)MSSQLSERVER2014.example.com