SqlDependency 클래스를 사용하여 변경 내용을 데이터베이스 테이블에서 모니터링하려고합니다. 나는 뭔가를 놓치고 있어야하지만. 온라인에서 볼 수있는 모든 예를 따라했으며이 사이트의 모든 질문을 검토했습니다. 나는 내가 잃어버린 것을 보지 못한다. 다음은 서비스 브로커를 활성화하고 대기열과 서비스를 만들기 위해 데이터베이스에서 실행 한 초기 명령입니다.Windows 서비스의 SqlDependency가 실행되지 않습니다.
CREATE QUEUE ScheduleChangeQueue
GO
CREATE SERVICE ScheduleChangeService ON QUEUE ScheduleChangeQueue ([http://schemas.microsoft.com/SQL/Notifications/PostQueryNotification])
GO
ALTER DATABASE [database] SET ENABLE_BROKER
C# 측에서 프로세스를 시작하기 위해 호출되는 단일 정적 설치 메서드가있는 클래스를 만들었습니다.
public class SqlDependencyManager
{
private static bool DoesUserHavePermission()
{
var success = false;
try
{
Program.Log.Info("Retrieving SqlPermission to establish dependency...");
var clientPermission = new SqlClientPermission(System.Security.Permissions.PermissionState.Unrestricted);
// this will throw an error if the user does not have the permissions
clientPermission.Demand();
success = true;
Program.Log.Info("SqlPermission established. Continue setting up dependency.");
}
catch (Exception ex)
{
Program.Log.Error(ex, "SqlPermission not able to be established.");
}
return success;
}
public static void Setup()
{
if (!DoesUserHavePermission())
{
return;
}
var connectionString = ConfigurationManager.ConnectionStrings["ShowMakerPro"].ConnectionString;
// You must stop the dependency before starting a new one.
// You must start the dependency when creating a new one.
SqlDependency.Stop(connectionString);
SqlDependency.Start(connectionString);
using (var cn = new SqlConnection(connectionString))
{
using (var cmd = cn.CreateCommand())
{
cmd.CommandType = CommandType.Text;
//cmd.CommandText = "SELECT MAX(LastChangeTime) FROM Schedule WHERE ChannelID IN (SELECT ID FROM Channels WHERE Type = 1) AND StartTime BETWEEN (GETDATE() - 7) AND (GETDATE() + 30)";
cmd.CommandText = "SELECT LastChangeTime FROM dbo.Schedule";
cmd.Notification = null;
// Creates a new dependency for the SqlCommand. Then creates attaches handler for the notification of data changes
new SqlDependency(cmd).OnChange += SqlDependency_OnChange;
cn.Open();
cmd.ExecuteReader();
}
}
Program.Log.Info("SQL Dependency set. Now monitoring schedule table for changes.");
}
private static void SqlDependency_OnChange(object sender, SqlNotificationEventArgs e)
{
if (e.Type == SqlNotificationType.Change)
{
// this will remove the event handler since the dependency is only for a single notification
((SqlDependency)sender).OnChange -= SqlDependency_OnChange;
ScheduleOutputterService.BuildSchedules();
Program.Log.Info("SQL Dependency triggered schedule rebuild. Resetting SqlDependency to monitor for changes.");
Setup();
}
}
}
내가 코드 가져 오기 설정이 확인보고 onchange를 방법은 구독에 대해 한 번 해고 그러나 나는 그것이 그 후 화재 볼 수 없습니다 : 여기에 대한 코드입니다. 나는 수동으로 데이터베이스에 가서 LastChangeTime 필드를 변경하여 이벤트 발사를 강요하지만 아무 일도 일어나지 않기를 바란다.
내가 실수 한 부분을 누군가가 밝힐 수 있습니까? 나는 어떤 사람들이 온라인으로이 창문 형태로 잘 작동한다고 말하지만 서비스 중에도 문제가있다.
당신은 당신의 OnChange에서이 댓글이 있습니다 종속성이 하나의 notification'만을위한 것입니다 어쩌면 그것은 이유는 이후'//이 이벤트 핸들러를 제거 할 것인가? – Serg
@Serg 이벤트가 발생할 때마다 종속성이 손상되므로 필수입니다. 후속 변경 사항이 계속 발생할 때마다 매번 다시 작성해야합니다. – spinon
어쩌면 레크리에이션이 작동하지 않을 수 있습니까? 내가 당신의 코드를 오해하면 미안 해요. – Serg