C# SQL依赖于基于连接数的更改事件触发
我刚刚尝试过实现sql依赖关系来检测表中的更改,就实现而言,我在更改表中的数据时就得到了触发器,但问题是我得到的触发器是基于连接数的。 例如,如果我的url在两个浏览器中打开,那么当表中有更改时,依赖更改事件会触发两次,如果它打开三次,那么依赖更改事件会触发三次,并且很快就会触发 这是我试过的代码C# SQL依赖于基于连接数的更改事件触发,c#,sql-server-2008,sqldependency,C#,Sql Server 2008,Sqldependency,我刚刚尝试过实现sql依赖关系来检测表中的更改,就实现而言,我在更改表中的数据时就得到了触发器,但问题是我得到的触发器是基于连接数的。 例如,如果我的url在两个浏览器中打开,那么当表中有更改时,依赖更改事件会触发两次,如果它打开三次,那么依赖更改事件会触发三次,并且很快就会触发 这是我试过的代码 private void GetUsers() { using (SqlConnection connection = new SqlCo
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");
}
任何帮助都将不胜感激。您希望看到的行为是什么?您的问题不清楚。我需要只触发一次依赖项更改事件,每次我更改tableFYI中的数据时,依赖项更改事件触发器的次数会随着页面刷新而增加。例如,如果我刷新页面两次,那么事件将触发两次,以此类推……是否每次加载页面时都调用GetUsers方法?如果是这样,这就是在每次调用该方法时向数据库注册一个通知。如果您只希望收到一次通知,则需要注意通知已注册,并作出相应的反应。但这是我的页面加载保护的无效页面\u Loadobject发件人,EventArgs e{If!this.IsPostBack{this.GetUsers;}