0

В последние дни у меня возникают проблемы с использованием SQL Dependency.SqlDependency fire правильно, но также и во время запуска

С образцом в this link У меня ПОЛНОСТЬЮ достигают цели. «Почти», потому что событие срабатывает правильно, но также и при запуске, когда я вызываю метод «Старт» класса MyService. Здесь есть мой код, но, как вы видите, это одно и то же (или почти) ссылка.

Я думаю, что могу просто вставить значение bool, только чтобы избежать события инициализации, но я думаю, что другое решение будет лучше.

SQLWatcher:

using System; 
using System.Collections.Generic; 
using System.Data; 
using System.Data.SqlClient; 
using System.Linq; 
using System.Text; 
using System.Threading; 
using System.Threading.Tasks; 

public enum SqlWatcherNotificationType 
{ 
    Blocking, 
    Threaded // Launch in another thread so SqlWatcher can immediately start monitoring again. 
} 

public class SqlWatcher : IDisposable 
{ 
    private string ConnectionString; 
    private SqlConnection Connection; 
    private SqlCommand Command; 
    private SqlDataAdapter Adapter; 
    private DataSet Result; 
    private SqlWatcherNotificationType NotificationType; 

    public SqlWatcher(string ConnectionString, SqlCommand Command, SqlWatcherNotificationType NotificationType) 
    { 
     this.NotificationType = NotificationType; 
     this.ConnectionString = ConnectionString; 
     SqlDependency.Start(this.ConnectionString); 
     this.Connection = new SqlConnection(this.ConnectionString); 
     this.Connection.Open(); 
     this.Command = Command; 
     this.Command.Connection = this.Connection; 
     Adapter = new SqlDataAdapter(this.Command); 
    } 

    public void Start() 
    { 
     RegisterForChanges(); 
    } 

    public void Stop() 
    { 
     SqlDependency.Stop(this.ConnectionString); 
    } 

    public delegate void SqlWatcherEventHandler(DataSet Result); 

    public event SqlWatcherEventHandler OnChange; 

    public DataSet DataSet 
    { 
     get { return Result; } 
    } 

    private void RegisterForChanges() 
    { 
     //Remove old dependency object 
     this.Command.Notification = null; 
     //Create new dependency object 
     SqlDependency dep = new SqlDependency(this.Command); 
     dep.OnChange += new OnChangeEventHandler(Handle_OnChange); 
     //Save data 
     Result = new DataSet(); 
     Adapter.Fill(Result); 
     //Notify client of change to DataSet 
     switch (NotificationType) 
     { 
      case SqlWatcherNotificationType.Blocking: 
       OnChange(Result); 
       break; 
      case SqlWatcherNotificationType.Threaded: 
       ThreadPool.QueueUserWorkItem(ChangeEventWrapper, Result); 
       break; 
     } 
    } 

    public void ChangeEventWrapper(object state) 
    { 
     DataSet Result = (DataSet)state; 
     OnChange(Result); 
    } 

    private void Handle_OnChange(object sender, SqlNotificationEventArgs e) 
    { 
     if (e.Type != SqlNotificationType.Change) 
      throw new ApplicationException("Failed to create queue notification subscription!"); 

     //Clean up the old notification 
     SqlDependency dep = (SqlDependency)sender; 
     dep.OnChange -= Handle_OnChange; 

     //Register for the new notification 
     RegisterForChanges(); 
    } 

    public void Dispose() 
    { 
     Stop(); 
    } 
} 

и это MyService класс:

public class MyService 
{ 
    private static SqlWatcher SqlQueueWatcher; 

    public static void Start() 
    { 
     string connS = MainWindow.dbContext.Database.Connection.ConnectionString + "Password=111;"; 
     //Build the command object we want to monitor (don't include a SqlConnection) 
     SqlCommand cmd = new SqlCommand(); 
     cmd = new SqlCommand("SELECT CODVEI FROM dbo.ArchivioErogazioni"); 
     cmd.CommandType = CommandType.Text; 

     //Setup the SQLWatcher 
     SqlQueueWatcher = new SqlWatcher(connS, cmd, SqlWatcherNotificationType.Blocking); 
     SqlQueueWatcher.OnChange += new SqlWatcher.SqlWatcherEventHandler(QueueSQLWatcher_OnChange); 
     SqlQueueWatcher.Start(); 
    } 

    private static void QueueSQLWatcher_OnChange(DataSet Result) 
    { 
     //Do something with the updated DataSet object 
     Debug.WriteLine("AAAAAAAAAAAAAAAAAAAAAAAAAAAAAA"); ---> ENTERS HERE IN THE INIT PHASE 
    } 

    public static void Stop() 
    { 
     SqlQueueWatcher.Dispose(); 
    } 
} 

и это, как я symply назвать это:

MyService.Start(); 

ли BOOL флаг плохая идея? Почему он вводит в QueueSQLWatcher_OnChange во время запуска?

ответ

0

Чтобы устранить эту проблему, вам нужно только установить для этого уведомления SqlCommand значение null.

cmd.Notification = null; 

Просто попробуйте это, и я думаю, что ваша проблема будет решена. Введите эту строку перед запуском зависимости, используя класс SqlWatcher