我对 SQL Server 中的查询通知概念不熟悉,需要一些时间来理解。
我的目标是创建一个 Windows 服务应用程序,在 SQL Server 表格发生更改时得到通知。 我遵循了这个指南,它对我的起步有所帮助。
然而,我无法获得预期的结果。我的 Windows 服务应用程序中的 OnStart()
方法如下:
protected override void OnStart(string[] args)
{
eventLog1.WriteEntry("Service Started");
serviceRun = false;
SqlClientPermission perm = new SqlClientPermission(System.Security.Permissions.PermissionState.Unrestricted);
try
{
perm.Demand();
eventLog1.WriteEntry("permission granted");
}
catch (System.Exception)
{
eventLog1.WriteEntry("permission denied");
}
try
{
connstr = "Data Source=THSSERVER-LOCAL;Initial Catalog=ET;User ID=mujtaba;Password=ths123";
connection = new SqlConnection(connstr);
SqlCommand command = new SqlCommand("select * from dbo.Customer_FileUploads", connection);
// Create a dependency and associate it with the SqlCommand.
SqlDependency dependency = new SqlDependency(command);
// Maintain the reference in a class member.
// Subscribe to the SqlDependency event.
dependency.OnChange += Dependency_OnChange;
SqlDependency.Start(connstr);
connection.Open();
// Execute the command.
using (SqlDataReader reader = command.ExecuteReader())
{
if (reader.HasRows)
{
while (reader.Read())
{
//eventLog1.WriteEntry("reading data");
}
}
else
{
eventLog1.WriteEntry("No rows found.");
}
reader.Close();
}
}
catch (Exception e)
{
eventLog1.WriteEntry("Error Message: " + e.Message);
}
}
事件
SqlDependency
的订阅方式如下:private void Dependency_OnChange(object sender, SqlNotificationEventArgs e)
{
// Handle the event.
eventLog1.WriteEntry("data changed");
}
OnStop()
方法如下:
protected override void OnStop()
{
SqlDependency.Stop(connstr);
connection.Close();
eventLog1.WriteEntry("In onStop.");
}
我的数据库中设置了ENABLE_BROKER
为true。最终结果是,服务运行并创建了以下日志:
"Service Started"
"permission granted"
"data changed"
然而,当我向表中插入新数据时,
OnChange()
事件不会触发,并且没有创建新日志。此外,当我停止并重新启动服务时, OnChange()
被触发,即使没有插入新数据。有人可以帮助我理解这个过程吗?