我刚刚尝试实现sql依赖来检测表中的更改,只要实现我在表中更改数据时就会获得触发器,但问题是我根据连接数得到触发器。 例如,如果我在2个浏览器中打开了我的url,那么当表中发生更改时,对change事件的依赖会被触发两次,如果它被打开三次,那么我的on change事件将被触发很快三次。
这是我尝试的代码。
private void GetUsers()
{
using (SqlConnection connection = new SqlConnection(connectionString))
{
using (SqlCommand command = connection.CreateCommand())
{
command.CommandType = CommandType.Text;
command.CommandText = "SELECT FirstName, LastName FROM dbo.[Users]";
command.Notification = null;
// creates a new dependency for the SqlCommand
SqlDependency dependency = new SqlDependency(command);
// 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
dependency.OnChange += new OnChangeEventHandler(Dependency_OnChange);
connection.Open();
List<UserInfo> userList = new List<UserInfo>();
using (IDataReader userDataReader = command.ExecuteReader())
{
if (userDataReader != null)
{
while (userDataReader.Read())
{
UserInfo userInfo = new UserInfo();
userInfo.FirstName = Convert.IsDBNull(userDataReader["FirstName"]) ? string.Empty : Convert.ToString(userDataReader["FirstName"]);
userInfo.LastName = Convert.IsDBNull(userDataReader["LastName"]) ? string.Empty : Convert.ToString(userDataReader["LastName"]);
userList.Add(userInfo);
}
}
}
if (userList != null && userList.Count > 0)
{
this.dgUserList.DataSource = userList;
this.dgUserList.DataBind();
}
}
}
}
private void Dependency_OnChange(object sender, SqlNotificationEventArgs e)
{
this.GetUsers();
// this will remove the event handler since the dependency is only for a single notification
SqlDependency dependency = sender as SqlDependency;
// NOTE: the following code uses the normal .Net capitalization methods, though
// the forum software seems to change it to lowercase letters
dependency.OnChange -= new OnChangeEventHandler(Dependency_OnChange);
// To broadcast my message
ChatHub chat = new ChatHub();
chat.send("myname", "New Registration Done");
}
非常感谢任何帮助。