2011-09-06 3 views
0

Windows 서비스 내 데이터베이스에서 삽입/업데이트 이벤트를 캡처하기 위해 SQL Server 알림을 사용하고 싶습니다. SQLDependency 개체를 사용하려고합니다. MSDN 기사를 보면이 사실이 꽤 솔직하게 보입니다. 그래서 그것을 시험해보기 위해 약간의 예제 애플리케이션을 만들었습니다. 테이블에 데이터를 변경할 때 OnChange 이벤트가 발생하지는 않습니다. 누군가 내가 놓친 걸 말해 줄 수 있니? 감사! 내 코드 샘플은 다음과 같습니다.SQL Server 알림 - 내 OnChange가 Windows 서비스에서 실행되지 않습니다.

private bool CanRequestNotifications() 
{ 
    SqlClientPermission permit = new 
    SqlClientPermission(System.Security.Permissions.PermissionState.Unrestricted); 
    try 
    { 
     permit.Demand(); 
     return true; 
    } 
    catch (System.Exception exc) 
    { 
     return false; 
    } 
} 

private void NotificationListener() 
{ 
    string mailSQL; 
    SqlConnection sqlConn; 
    try 
    { 
     string connString = "Data Source=xyz;Initial Catalog=abc;User ID=sa;Password=******"; 
     mailSQL = "SELECT * FROM [tbl_test]"; 

     SqlDependency.Stop(connString); 
     SqlDependency.Start(connString); 

     sqlConn = new SqlConnection(connString); 
     SqlCommand sqlCmd = new SqlCommand(mailSQL, sqlConn); 
     this.GetNotificationData(); 
     evtLog.WriteEntry("Error Stage: NotificationListener" + "Error desc:" + "Message", EventLogEntryType.Error); 
    } 
    catch (Exception e) 
    { 
     // handle exception 
    } 
} 

private void GetNotificationData() 
{ 
    DataSet myDataSet = new DataSet(); 
    SqlCommand sqlCmd = new SqlCommand(); 
    sqlCmd.Notification = null; 

    SqlDependency dependency = new SqlDependency(sqlCmd); 
    dependency.OnChange += new OnChangeEventHandler(dependency_OnChange); 
    evtLog.WriteEntry("Error Stage: GetNotificationData" + "Error desc:" + "Message", EventLogEntryType.Error); 
} 

private void dependency_OnChange(object sender,SqlNotificationEventArgs e) 
{ 
    SqlDependency dependency = (SqlDependency)sender; 
    dependency.OnChange -= dependency_OnChange; 
    this.GetNotificationData(); 
    evtLog.WriteEntry("Error Stage: dependency_OnChange" + "Error desc:" + "Message", EventLogEntryType.Error); 
} 

protected override void OnStart(string[] args) 
{ 
    CanRequestNotifications(); 
    NotificationListener(); 
} 

protected override void OnStop() 
{ 
    SqlDependency dependency = new SqlDependency(); 
    dependency.OnChange -= dependency_OnChange; 
    SqlDependency.Stop(connString); 
} 

답변

0

당신이 각 작업에 대한 새로운 SqlDependency 인스턴스를 사용하고있는 것 같다 -이 장기적으로 작동하지 않습니다; 필요한 코드 부분에 액세스 할 수있는 단일 인스턴스에 대한 참조가 있어야합니다. 이는 문제 해결에 도움이 될 수 있습니다.

또한 데이터를 변경하고 연결 및 명령을 만들었지 만 실행되지는 않습니다.

+0

인스턴스를 단일 인스턴스로 변경했습니다. 그리고 서비스가 진행되는 동안 SQL 관리 스튜디오를 사용하여 데이터베이스에 직접 테이블을 변경합니다. 또한 나는이 Windows 응용 프로그램에서 시도하고 괜찮 았는데. – user930596

+0

많은 사람들이 dependency_OnChange() 이벤트에서 NotificationListener()를 호출해야하는 것과 같은 전략을 가지고있는 것을 보았습니다. 단지 시도. – Thomas

관련 문제