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

时间:2016-07-28 07:24:48

标签: c# asp.net sql-server-2014 monitor sqldependency

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

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

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

2-如果我在'用户'中添加或删除一行在SQL Server Management Studio中,它触发了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);
        }

任何帮助都将受到高度赞赏。

1 个答案:

答案 0 :(得分:0)

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