【问题标题】:SqlDependency in Windows Form application is fast, but it is slow in ASP.net MVC applicationWindows 窗体应用程序中的 SqlDependency 很快,但在 ASP.net MVC 应用程序中很慢
【发布时间】:2016-07-28 07:24:48
【问题描述】:

我编写了一个 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);
        }

任何帮助将不胜感激。

【问题讨论】:

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


    【解决方案1】:

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

    【讨论】:

    • 感谢您的回答。问题是否与连接字符串有关?
    • 其实,目前我的连接字符串是“Data Source=VIUNA_PC\MSSQLSERVER2014 ....”
    • 并非如此。我可能无法正确解释它,但我在尝试使用 WINS 时有类似的经历,每次它必须联系 SQL 服务器时都会减慢我的应用程序的速度。经过一番研究,我能够通过更改为 FQDN 来做到这一点。 MSSQLSERVER2014 是实例名称,然后使用 VIUNA_PC 的 FQDN
    猜你喜欢
    • 2020-12-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-10-17
    • 2023-04-04
    • 1970-01-01
    相关资源
    最近更新 更多