using System; using System.Collections.Generic; using System.Data; namespace Lskj.Util { /// /// 单次模块初始化期间复用的参数缓存。 /// public static class InitialParamCache { private static readonly object SyncRoot = new object(); private static readonly Dictionary TableExistsCache = new Dictionary(StringComparer.OrdinalIgnoreCase); private static readonly Dictionary ColumnExistsCache = new Dictionary(StringComparer.OrdinalIgnoreCase); private static readonly Dictionary TableColumnsCache = new Dictionary(StringComparer.OrdinalIgnoreCase); /// /// 获取表是否存在。没有缓存时执行查询,并记录查询结果。 /// public static bool GetTableExists(string tableName, Func query) { if (string.IsNullOrWhiteSpace(tableName)) { throw new ArgumentException("表名不能为空。", "tableName"); } if (query == null) { throw new ArgumentNullException("query"); } lock (SyncRoot) { bool tableExists; if (TableExistsCache.TryGetValue(tableName, out tableExists)) { return tableExists; } tableExists = query(); TableExistsCache[tableName] = tableExists; return tableExists; } } /// /// 获取字段是否存在。没有缓存时执行查询,并记录查询结果。 /// public static bool GetColumnExists(string tableName, string columnName, string columnType, Func query) { if (string.IsNullOrWhiteSpace(tableName)) { throw new ArgumentException("表名不能为空。", "tableName"); } if (string.IsNullOrWhiteSpace(columnName)) { throw new ArgumentException("字段名不能为空。", "columnName"); } if (query == null) { throw new ArgumentNullException("query"); } string cacheKey = tableName + "|" + columnName + "|" + (columnType ?? string.Empty); lock (SyncRoot) { bool columnExists; if (ColumnExistsCache.TryGetValue(cacheKey, out columnExists)) { return columnExists; } columnExists = query(); ColumnExistsCache[cacheKey] = columnExists; return columnExists; } } /// /// 获取表结构。没有缓存时执行查询,并缓存不包含数据的结构模板。 /// public static DataTable GetTableColumns(string tableName, Func query) { if (string.IsNullOrWhiteSpace(tableName)) { throw new ArgumentException("表名不能为空。", "tableName"); } if (query == null) { throw new ArgumentNullException("query"); } lock (SyncRoot) { DataTable tableColumns; if (!TableColumnsCache.TryGetValue(tableName, out tableColumns)) { DataTable queryResult = query(); if (queryResult == null) { throw new InvalidOperationException("获取表结构失败。" + tableName); } tableColumns = queryResult.Clone(); TableColumnsCache[tableName] = tableColumns; } return tableColumns.Clone(); } } /// /// 清空上一次模块初始化记录的参数。 /// public static void Clear() { lock (SyncRoot) { TableExistsCache.Clear(); ColumnExistsCache.Clear(); TableColumnsCache.Clear(); } } } }