在 SQL 依赖项更改后调用客户端函数
本文关键字:调用 客户端 函数 SQL 依赖 | 更新日期: 2023-09-27 18:36:30
我正在使用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 只有在发生回发时才起作用。此处未发生回发。整个事情的主要目的是避免回发:)
使用 SignalR :) 解决了这个问题SignalR + SQLDependency 是一个踢屁股的配方:)快乐编码