我在Windows服务中使用了sql依赖关系,它将监视学生表中的更改。学生表中的任何更改都应通知Windows服务,之后该服务即可完成工作。
即使在表中进行了多次更改,在Web应用程序中尝试相同的代码也可以正常工作。但是当作为Windows服务托管时,当我尝试将流程附加到调试时,仅第一个更改会收到通知,而后续更改不会影响Windows服务。
可能是什么问题?
protected override void OnStart(string[] args)
{
SqlDependency.Stop(connString);
//Start SqlDependency with application initialization
SqlDependency.Start(connString);
StudentService studentService = new StudentService();
studentService.GetStudentDetails();
}
protected override void OnStop()
{
//Stop SqlDependency
SqlDependency.Stop(connString);
}
public static List<Student> GetStudentRecords()
{
var lstStudentRecords = new List<Student>();
string dbConnectionSettings = ConfigurationManager.ConnectionStrings["DefaultConnection"].ConnectionString;
using (var dbConnection = new SqlConnection(dbConnectionSettings))
{
dbConnection.Open();
var sqlCommandText = @"SELECT [StudentID],[StudentName],[DOB],[Weight] FROM [dbo].[Student]";
using (var sqlCommand = new SqlCommand(sqlCommandText, dbConnection))
{
AddSQLDependency(sqlCommand);
if (dbConnection.State == ConnectionState.Closed)
dbConnection.Open();
var reader = sqlCommand.ExecuteReader();
lstStudentRecords = GetStudentRecords(reader);
}
}
return lstStudentRecords;
}
private static void AddSQLDependency(SqlCommand sqlCommand)
{
sqlCommand.Notification = null;
var dependency = new SqlDependency(sqlCommand);
dependency.OnChange += (sender, sqlNotificationEvents) =>
{
if (sqlNotificationEvents.Type == SqlNotificationType.Change)
{
HitHere(sqlNotificationEvents.Info);
}
};
}