Created
January 13, 2018 18:21
-
-
Save hbulens/bb7b5af043538531aacda6cde82805ad to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
public class DatabaseChangeListener | |
{ | |
#region Constructor | |
public DatabaseChangeListener(string connectionString) | |
{ | |
this.connectionString = connectionString; | |
SqlDependency.Stop(connectionString); | |
SqlDependency.Start(connectionString); | |
connection = new SqlConnection(connectionString); | |
} | |
#endregion Constructor | |
# region Finalizer | |
~DatabaseChangeListener() | |
{ | |
SqlDependency.Stop(connectionString); | |
} | |
# | |
endregion Finalizer | |
# region Properties | |
private readonly string connectionString; | |
private readonly SqlConnection connection; | |
public delegate void NewMessage(); | |
public event NewMessage OnChange; | |
#endregion Properties | |
#region Methods | |
public DataTable Start(string changeQuery) | |
{ | |
using(SqlCommand cmd = new SqlCommand(changeQuery, connection) {Notification = null}) | |
{ | |
SqlDependency dependency = new SqlDependency(cmd); | |
dependency.OnChange += NotifyOnChange; | |
if (connection.State == ConnectionState.Closed) | |
{ | |
connection.Open(); | |
} | |
using(DataTable dt = new DataTable()) | |
{ | |
dt.Load(cmd.ExecuteReader(CommandBehavior.CloseConnection)); | |
return dt; | |
} | |
} | |
} | |
void NotifyOnChange(object sender, SqlNotificationEventArgs e) | |
{ | |
var dependency = sender as SqlDependency; | |
if (dependency != null) dependency.OnChange -= NotifyOnChange; | |
if (OnChange != null) | |
{ | |
OnChange(); | |
} | |
} | |
#endregion Methods | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment