我正在使用 SqlDependency 来控制我的缓存。我想用它来监控几个表(大约 10 个)。每个监视表应该有一个 SqlDependency。
我应该为他们每个人创建这样的代码:
public void CreateDependency_Table()
{
if (connectionStringSettings != null)
{
using (SqlConnection conn = new SqlConnection(connectionStringSettings.ConnectionString))
{
conn.Open();
using (SqlCommand cmd = new SqlCommand("SELECT id from dbo.Table", conn))
{
cmd.Notification = null;
SqlDependency sqlDependency = new SqlDependency(cmd);
sqlDependency.OnChange += new OnChangeEventHandler(sqlDep_Table_OnChange);
using (SqlDataReader reader = cmd.ExecuteReader(CommandBehavior.CloseConnection))
{
}
}
}
}
}
和:
private void sqlDep_Table_OnChange(object sender, SqlNotificationEventArgs e)
{
SqlDependency dependency = (SqlDependency)sender;
dependency.OnChange -= sqlDep_Table_OnChange;
MyCacheWhatever.Clear();
//Re-attach dependency
CreateDependency_Table();
}
或者我可以重用它们之间的东西吗?喜欢连接?
这是设置多个通知的首选方式吗?
最佳答案
在这里,我将向您展示一个可能对您有所帮助的 linq 扩展:
public static class LinqExtensions
{
private static ILog _Log = LogManager.GetLogger(MethodInfo.GetCurrentMethod().DeclaringType);
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes")]
public static IList<T> LinqCache<T>(this Table<T> query) where T : class
{
string tableName = query.Context.Mapping.GetTable(typeof(T)).TableName;
IList<T> result = HttpContext.Current.Cache[tableName] as List<T>;
if (result == null)
{
try
{
using (SqlConnection cn = new SqlConnection(query.Context.Connection.ConnectionString))
{
cn.Open();
SqlCommand cmd = new SqlCommand(query.Context.GetCommand(query).CommandText, cn);
cmd.Notification = null;
cmd.NotificationAutoEnlist = true;
_Log.DebugFormat("Attempting to enable sql cache dependency notifications for table {0}", tableName);
SqlCacheDependencyAdmin.EnableNotifications(query.Context.Connection.ConnectionString);
string[] tables = SqlCacheDependencyAdmin.GetTablesEnabledForNotifications(query.Context.Connection.ConnectionString);
if (!tables.Contains(tableName))
SqlCacheDependencyAdmin.EnableTableForNotifications(query.Context.Connection.ConnectionString, tableName);
_Log.DebugFormat("Sql cache dependency notifications for table {0} is enabled.", tableName);
SqlCacheDependency dependency = new SqlCacheDependency(cmd);
cmd.ExecuteNonQuery();
result = query.ToList();
HttpContext.Current.Cache.Insert(tableName, result, dependency);
_Log.DebugFormat("Table {0} is cached.", tableName);
}
}
catch (Exception ex)
{
result = query.Context.GetTable<T>().ToList();
HttpContext.Current.Cache.Insert(tableName, result);
string msg = string.Format(CultureInfo.InvariantCulture,
"Table {0} is cached without SqlCacheDependency!!!", tableName);
_Log.Warn(msg, ex);
}
}
return result;
}
}
关于asp.net - asp.net中的SqlDependency,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3422080/