我創建了以下封裝在SQL依賴對象:的SqlDependency在ASP.NET
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;
}
}
}
它不是一個原創作品,它是基於this text.從我的倉庫我做了以下內容:
public bool Updatexxx(Ixxx xsxs)
{
try
{
SqlConnection sqlConn = new SqlConnection(_ConnectionString);
sqlConn.Open();
...
bool result = sqlComm.ExecuteNonQuery() == 1;
_ResetEvent.WaitOne();
return result;
}
catch ...
catch ...
}
回調是
public void RefreshData()
{
FindAllxxx();
_ResetEvent.Set();
}
而且
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;
}
和FindAllXXXNonCached()從數據庫中進行真正的選擇。如你所見,我正在緩存所有內容。我的問題是爲什麼這不起作用。 症狀:從依賴跟蹤器回調被調用兩次然後它阻止。我實現了這一點,因爲我的通知是在頁面刷新開始之後發佈的。我試圖通過手動重置事件來給通知一個機會,然後設置手動重置事件並刷新UI。正如我所說的,在經過兩次OnChange之後,它會凍結。我能做什麼? Dependency Tracker在Unity容器中實例註冊,Repository是類型註冊的。
是否因爲存儲類型已註冊,未註冊實例?順便說一句,我確實在每個容器中設置了依賴關係跟蹤器的回調。 – DaeMoohn 2009-10-12 16:25:45