Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
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
You can’t perform that action at this time.