缓存更新类如下:
/// <summary> /// 缓存更新类 /// </summary> /// <typeparam name="T">缓存对象</typeparam> public class UpdateCacheHelper<T> { /// <summary> /// 计时器 /// </summary> private System.Threading.Timer timer; /// <summary> /// 缓存时间(分钟) /// </summary> private int saveTime; /// <summary> /// 默认(毫秒) /// </summary> private int intervalTime = 10 * 1000; /// <summary> /// 缓存键 /// </summary> private string cacheKey = string.Empty; /// <summary> /// 代理 /// </summary> private Delegate dele; /// <summary> /// 代理的入参 /// </summary> private object[] objs; /// <summary> /// 更新缓存类 /// </summary> /// <param name="dele">代理</param> /// <param name="cacheKey">key</param> /// <param name="saveTime">缓存时间(分钟)</param> /// <param name="intervalTime">间隔时间(秒)</param> /// <param name="objs">入参</param> public UpdateCacheHelper(Delegate dele, string cacheKey, int saveTime, int intervalTime, params object[] objs) { this.dele = dele; this.cacheKey = cacheKey; this.saveTime = saveTime; this.intervalTime = intervalTime * 1000; this.objs = objs; this.timer = new System.Threading.Timer(new System.Threading.TimerCallback(this.CheckDependencyCallBack), this, 0, this.intervalTime); } /// <summary> /// 从数据库获取数据 /// </summary> /// <returns>数据</returns> public T GetData() { string assemblyName = this.dele.Target.GetType().Assembly.FullName; string typeName = this.dele.Target.GetType().FullName; object instance = Assembly.Load(assemblyName).CreateInstance(typeName); MethodInfo methodInfo = this.dele.Method; return (T)methodInfo.Invoke(instance, this.objs); } /// <summary> /// 回调函数 /// </summary> /// <param name="sender">sender</param> private void CheckDependencyCallBack(object sender) { T newData = this.GetData(); HttpRuntime.Cache.Insert(this.cacheKey, newData, null, Cache.NoAbsoluteExpiration, new TimeSpan(0, this.saveTime, 0), CacheItemPriority.NotRemovable, null); } }