"행 수 계산"쿼리 (C#, SQL Server 2008 Express로 작성)에서 실행되도록 SQL 종속성을 설정하려고 시도했지만 원래 구독 SQLNotificationType이 실행 된 후에는 이벤트 처리기가 행을 추가 했음에도 불구하고 다시 실행하고 싶습니다. 그리고 SQL을 확인한 후 예상 값을 반환합니다 ...).SQL 종속성이 실행되지 않음
내 코드는 다음과 같습니다. 어떤 생각이라도 대단히 감사합니다!
편집 :이 코드가 포함 된 프로젝트는 WPF 프로그램입니다. 이 특정 코드는 별도의 클래스에 저장되어 있습니다.이 WPF 프로그램은 'Initialized'이벤트 처리기에서 인스턴스를 만듭니다. 그런 다음이 클래스에서 기본적으로 ConnectToDatabase()를 먼저 호출 한 다음 SetupSQLDependency()를 호출하는 메서드가 있습니다.
EDIT 2 : 부가 메모로,이 프로그램은 몇 명의 사용자에게 배포하기를 원했던 WPF입니다. 목표는 새로운 행이 데이터베이스에 추가 될 때마다 WPF가 특정 정보로 업데이트되도록하는 것이 었습니다. 나는 항상 데이터베이스를 쿼리하는 것과는 반대로이 방법이 최선의 방법이라고 생각했습니다.
private void ConnectToDatabase()
{
//This method is the first to be called, and is the entry
// point into my SQL database code.
databaseConnection = new SqlConnection(connectionString);
// Setup command used in SqlDependecy
SqlCommand tempCmd = new SqlCommand();
tempCmd.Connection = databaseConnection;
tempCmd.CommandText = "SELECT COUNT(ID) FROM [Example].[dbo].[ExampleTable]";
sqlCmd = tempCmd;
try
{ databaseConnection.Open(); }
catch (Exception e)
{ writeDebug(e.ToString()); }
}
private void SetupSQLDependency()
{
SqlDependency.Stop(connectionString);
SqlDependency.Start(connectionString);
sqlCmd.Notification = null;
// create new dependency for SqlCommand
SqlDependency sqlDep = new SqlDependency(sqlCmd);
sqlDep.OnChange += new OnChangeEventHandler(sqlDep_OnChange);
SqlDataReader reader = sqlCmd.ExecuteReader();
}
private void sqlDep_OnChange(object sender, SqlNotificationEventArgs e)
{
// FROM: http://msdn.microsoft.com/en-us/a52dhwx7.aspx
if (e.Type == SqlNotificationType.Change)
{
//++++++ THIS IS THE BLOCK THAT IS NEVER TRIGGERED ++++++//
// Have to remove this as it only work's once
SqlDependency sqlDep = sender as SqlDependency;
sqlDep.OnChange -= sqlDep_OnChange;
// Resetup Dependecy
SetupSQLDependency();
}
else if (e.Type == SqlNotificationType.Subscribe)
{
double te = 12; // Used this just to test a break... code is useless
}
}
이 코드가 어디에 존재하는지에 대해 자세히 설명해 줄 수 있습니까? 예를 들어,이 코드가'Page'에 존재하고'OnLoad' 이벤트에서 호출된다면, 페이지가 렌더링되고 나서 완전히 새로운 클래스가 생성되는 동안 페이지 클래스가 단지 잠시 동안 살아 있다는 것을 기억해야합니다 각 요청에 대해 인스턴스화됩니다. 따라서 이벤트 구독과 'sqlCmd' 변수 인스턴스는 유지되지 않습니다 (그리고 이론적으로 mem 누수가 발생합니다). – CodingGorilla
위의 편집을 완료했습니다. – keynesiancross
확인을 위해, 나는 당신이 ASP.NET에서 이것을하고 있다고 생각했습니다. 'SqlNotificationType.Change'는 한 번만 또는 한 번만 실행되거나 전혀 실행되지 않습니다. – CodingGorilla