【发布时间】:2014-12-23 12:17:52
【问题描述】:
当有人更新数据库中的数据时,我需要告诉我的应用程序。如果我没有误解,SqlDependancy 就是我需要的。我已经关注this tutorial 并编写了这段代码:
class dbListener
{
public dbListener()
{
Debug.WriteLine(MainWindow.dbContext.Database.Connection.ConnectionString + "Password=12345;");
SqlDependency.Start(MainWindow.dbContext.Database.Connection.ConnectionString + "Password=12345;");
connection = new SqlConnection(MainWindow.dbContext.Database.Connection.ConnectionString + "Password=12345;");
connection.Open();
SomeMethod();
}
SqlConnection connection;
void SomeMethod()
{
// Assume connection is an open SqlConnection.
// Create a new SqlCommand object.
//{
using (SqlCommand command = new SqlCommand("SELECT * FROM dbo.ArchivioErogazioni", connection))
{
// Create a dependency and associate it with the SqlCommand.
SqlDependency dependency = new SqlDependency(command);
// Maintain the refence in a class member.
// Subscribe to the SqlDependency event.
dependency.OnChange += new OnChangeEventHandler(OnDependencyChange);
// Execute the command.
command.ExecuteReader();
// }
}
}
// Handler method
void OnDependencyChange(object sender, SqlNotificationEventArgs e)
{
if (e.Type == SqlNotificationType.Change)
{
// Handle the event (for example, invalidate this cache entry).
MessageBox.Show("ikjkjkj");
Debug.WriteLine("fkldjkfjklgjf");
SqlDependency dependency = (SqlDependency)sender;
dependency.OnChange -= OnDependencyChange;
SomeMethod();
}
}
void Termination()
{
// Release the dependency.
SqlDependency.Stop(MainWindow.GetConnectionString("Model"));
}
}
但它不起作用。我的意思是,它运行时没有错误,但是当我尝试测试它,从 SQL Server 2008 Management Studio 更新一些值时,什么也没有发生。我在管理事件的函数中设置了一个断点,但它只在初始化阶段触发。
我做错了吗?我怎样才能达到我的目标?
【问题讨论】:
标签: sql-server-2008 notifications messaging service-broker sqldependency