public void Start() { _SynchronizationContext = SynchronizationContext.Current; if (ConString == "" || TableName == "" || CmdText == "") { return; } switch (IsManyService) { case true: SqlDependency.Start(ConString); break; default: SqlDependency.Stop(ConString); SqlDependency.Start(ConString); break; } try { if (Connection == null) { Connection = new SqlConnection(ConString); } Command = new SqlCommand(CmdText, Connection); if (dataToWatch == null) { dataToWatch = new DataSet(); } dataToWatch.Clear(); Command.Notification = null; Dependency = new SqlDependency(Command); //https://stackoverflow.com/questions/20503286/using-sqldependency-with-named-queues Dependency.OnChange += Dependency_OnChange; using (SqlDataAdapter adapter = new SqlDataAdapter(Command)) { adapter.Fill(dataToWatch, TableName); } //OnSqlChangeData(Dependency, null); SqlChange?.Invoke(this, new SqlChangeEventArgs() { TableDataSet = dataToWatch }); } catch (Exception) { throw; } }
public void OnSqlChangeData(object sender, SqlNotificationEventArgs e) { Dependency = (SqlDependency)sender; Dependency.OnChange -= Dependency_OnChange; if (e.Type != SqlNotificationType.Change) { return; } dataToWatch.Clear(); Command.Notification = null; Dependency = new SqlDependency(Command); Dependency.OnChange += Dependency_OnChange; using (SqlDataAdapter adapter = new SqlDataAdapter(Command)) { adapter.Fill(dataToWatch, TableName); } SqlChange?.Invoke(this, new SqlChangeEventArgs() { TableDataSet = dataToWatch }); }