Hi, I created the following encapsulation over the SQL Dependency object:
public class DependencyTracker
{
private SqlDependency _SQLDependency = null;
public string ConnectionString
{ get; private set; }
public string CommandNotifier
{ get; private set; }
public delegate void Refresh();
public event Refresh OnRefresh;
public DependencyTracker(string connectionString, string commandNotifier)
{
ConnectionString = connectionString;
CommandNotifier = commandNotifier;
}
public void StartDependency()
{
SqlDependency.Start(ConnectionString);
}
public void StopDependency()
{
SqlDependency.Stop(ConnectionString);
}
public void TrackForChanges()
{
using (SqlConnection sqlConn = new SqlConnection(ConnectionString))
{
sqlConn.Open();
using (SqlCommand sqlCommand = new SqlCommand(CommandNotifier, sqlConn))
{
sqlCommand.CommandType = CommandType.StoredProcedure;
_SQLDependency = new SqlDependency(sqlCommand);
_SQLDependency.OnChange += new OnChangeEventHandler(dependency_OnChange);
sqlCommand.ExecuteReader();
}
}
}
void dependency_OnChange(object sender, SqlNotificationEventArgs e)
{
SqlDependency sqlDependency = (SqlDependency)sender;
sqlDependency.OnChange -= dependency_OnChange;
if (OnRefresh != null)
{
OnRefresh();
}
}
public bool HasChanges
{
get
{
return _SQLDependency.HasChanges;
}
}
}
It's not an original work, it's based on this text. From my repository I do the following:
public bool Updatexxx(Ixxx xsxs)
{
try
{
SqlConnection sqlConn = new SqlConnection(_ConnectionString);
sqlConn.Open();
...
bool result = sqlComm.ExecuteNonQuery() == 1;
_ResetEvent.WaitOne();
return result;
}
catch ...
catch ...
}
The callback is
public void RefreshData()
{
FindAllxxx();
_ResetEvent.Set();
}
And
public HashSet<Iddd> Finddadas()
{
DependencyTracker tracker = _Container.Resolve<DependencyTracker>("dada");
UnityHashSet<IT24Route> hash = _Container.Resolve<UnityHashSet<dadas>>("Tdsadas");
if (tracker.HasChanges || hash.Count == 0)
{
hash = new UnityHashSet<dsda>(_Container);
hash.ImportHashSet(FindAlldsdsNonCached());
_Container.RegisterInstance<UnityHashSet<dsds>>("dasda", hash);
tracker.TrackForChanges();
}
return hash;
}
and FindAllXXXNonCached() does the real select from database. As you see, I am caching everything. My question is why does this NOT work. The symptom: from dependecy tracker the callback is called twice then it block. I implemented this because my notifications were coming after the refresh of the page began. I tried to put a manual reset event to give notification a chance, then set the manual reset event and the refresh the UI. As I said, after passing twice through the OnChange, it freezes. What can I do? Dependency Tracker is instance registered in Unity container, Repository is type registered.