以下c#代码是我所拥有的剥离版本。这基本上使用memory cache
缓存数据和AbsoluteExpiration
值决定何时清除缓存。一切都按预期工作。但是,最近,我必须在singleton
数据结构中包含以下代码。这给我留下了一些问题;
如何在多线程场景中工作, 当我的单例对象被并行访问时?
ObjectCache cache = MemoryCache.Default; if (cache.Contains(”UniqueKey”)) return cache.Get(”UniqueKey”); var dataToCache = GetData();//This is the data that I cache var policy = new CacheItemPolicy {AbsoluteExpiration = DateTime.Now.AddMinutes(int.Parse(ConfigurationManager.AppSettings["CacheExpiry"]))}; cache.Add(”UniqueKey”, dataToCache, policy); return dataToCache;