0

我正在使用 SqlDependency 来监视特定数据库表的更改。触发更改事件后,我需要调用 javascript 事件!任何的想法 ?这段代码在我的asp.net页面代码后面

    public void StartTasksMonitor()
    {
        var con = new SqlConnection { ConnectionString = ConfigurationManager.ConnectionStrings["connStr"].ConnectionString };

            if (con.State== System.Data.ConnectionState.Closed)
            {
                con.Open();
            }
            var cmd = new SqlCommand { CommandText = @"SELECT Id
      ,AssignedBy
      ,DateAssigned
      ,AssignedTo
      ,Title
      ,Description
      ,Completed
      ,DateDue
      ,Deleted
      ,DateDeleted
  FROM dbo.Tasks", Connection = con, Notification = null };

            SqlDependency dependency = new SqlDependency(cmd);
            SqlDataReader reader = cmd.ExecuteReader();
            con.Close();
            dependency.OnChange += new OnChangeEventHandler(dependency_OnChange);


    }

    void dependency_OnChange(object sender, SqlNotificationEventArgs e)
    {
        if (e.Type == SqlNotificationType.Change)
        {
            // Have to remove this as it only work's once
            SqlDependency sqlDep = sender as SqlDependency;
            sqlDep.OnChange -= dependency_OnChange;

            // Resetup Dependecy
            StartTasksMonitor();
            string clientFunc = @"alert('test')";

            ScriptManager.RegisterStartupScript(this, GetType(), "alert", clientFunc , true);


        }

    }

RegisterStartupScript 仅在回发发生时才起作用。这里没有回发。整个事情的主要目的是避免回发:)

4

1 回答 1

0

使用 SignalR 解决了这个问题 :) SignalR + SQLDependency 是一个绝妙的秘诀 :) 快乐编码

于 2013-10-31T07:48:51.130 回答