在控制台应用程序中缓存

我需要缓存一个通用列表,所以我不必多次查询数据库。 在Web应用程序中,我只需将其添加到httpcontext.current.cache 。 在控制台应用程序中缓存对象的正确方法是什么?

将它保留为包含类的实例成员。 在Web应用程序中,您无法执行此操作,因为在每个请求上都会重新创建页面类的对象。

但是,.NET 4.0也有用于此目的的MemoryCache类。

在类级变量中。 据推测,在控制台应用程序的main方法中,您实例化至少一个某种对象。 在此对象的类中,您声明了一个类级变量( List或其他),您可以在其中缓存任何需要缓存的内容。

这是我在控制台中使用的一个非常简单的缓存类,它具有自我清理和易于实现的function。

用法:

 return Cache.Get("MyCacheKey", 30, () => { return new Model.Guide().ChannelListings.BuildChannelList(); }); 

class级:

  using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Timers; namespace MyAppNamespace { public static class Cache { private static Timer cleanupTimer = new Timer() { AutoReset = true, Enabled = true, Interval = 60000 }; private static readonly Dictionary internalCache = new Dictionary(); static Cache() { cleanupTimer.Elapsed += Clean; cleanupTimer.Start(); } private static void Clean(object sender, ElapsedEventArgs e) { internalCache.Keys.ToList().ForEach(x => { try { if (internalCache[x].ExpireTime <= e.SignalTime) { Remove(x); } } catch (Exception) { /*swallow it*/ } }); } public static T Get(string key, int expiresMinutes, Func refreshFunction) { if (internalCache.ContainsKey(key) && internalCache[key].ExpireTime > DateTime.Now) { return (T)internalCache[key].Item; } var result = refreshFunction(); Set(key, result, expiresMinutes); return result; } public static void Set(string key, object item, int expiresMinutes) { Remove(key); internalCache.Add(key, new CacheItem(item, expiresMinutes)); } public static void Remove(string key) { if (internalCache.ContainsKey(key)) { internalCache.Remove(key); } } private struct CacheItem { public CacheItem(object item, int expiresMinutes) : this() { Item = item; ExpireTime = DateTime.Now.AddMinutes(expiresMinutes); } public object Item { get; private set; } public DateTime ExpireTime { get; private set; } } } } 
 // Consider this psuedo code for using Cache public DataSet GetMySearchData(string search) { // if it is in my cache already (notice search criteria is the cache key) string cacheKey = "Search " + search; if (Cache[cacheKey] != null) { return (DataSet)(Cache[cacheKey]); } else { DataSet result = yourDAL.DoSearch(search); Cache[cacheKey].Insert(result); // There are more params needed here... return result; } } 

参考: 如何缓存数据集以停止到db的往返?

根据您的具体操作,有许多方法可以实现缓存。 通常,您将使用字典来保存缓存的值。 这是我的缓存的简单实现,它只在有限的时间内缓存值:

 using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace CySoft.Collections { public class Cache { private readonly Dictionary _cache = new Dictionary(); private TimeSpan _maxCachingTime; ///  /// Creates a cache which holds the cached values for an infinite time. ///  public Cache() : this(TimeSpan.MaxValue) { } ///  /// Creates a cache which holds the cached values for a limited time only. ///  /// Maximum time for which the a value is to be hold in the cache. public Cache(TimeSpan maxCachingTime) { _maxCachingTime = maxCachingTime; } ///  /// Tries to get a value from the cache. If the cache contains the value and the maximum caching time is /// not exceeded (if any is defined), then the cached value is returned, else a new value is created. ///  /// Key of the value to get. /// Function creating a new value. /// A cached or a new value. public TValue Get(TKey key, Func createValue) { CacheItem cacheItem; if (_cache.TryGetValue(key, out cacheItem) && (DateTime.Now - cacheItem.CacheTime) <= _maxCachingTime) { return cacheItem.Item; } TValue value = createValue(); _cache[key] = new CacheItem(value); return value; } private struct CacheItem { public CacheItem(TValue item) : this() { Item = item; CacheTime = DateTime.Now; } public TValue Item { get; private set; } public DateTime CacheTime { get; private set; } } } } 

您可以将lambda表达式传递给Get方法,该方法例如从db中检索值。

您可以只使用一个简单的词典。 使Cache在Web环境中如此特殊的原因在于它持久存在并且范围很广,许多用户都可以访问它。 在控制台应用程序中,您没有这些问题。 如果您的需求足够简单,可以使用字典或类似结构快速查找从数据库中提取的值。