I am using Enterprise Library Caching block without configuration file. Cache settings are initialized from my code. I initialize the cache with the following code:
static class LocalCache
{
private static readonly CacheManager CacheManager;
static LocalCache()
{
try
{
string localCacheName = "MyCache";
DictionaryConfigurationSource configSource = new DictionaryConfigurationSource();
CacheManagerSettings cacheSettings = new CacheManagerSettings();
configSource.Add(CacheManagerSettings.SectionName, cacheSettings);
CacheStorageData storageConfig = new CacheStorageData("NoStorage", typeof(NullBackingStore));
cacheSettings.BackingStores.Add(storageConfig);
var expirationPollFrequencyInSeconds = 2;
CacheManagerData cacheManagerData = new CacheManagerData(
localCacheName,
expirationPollFrequencyInSeconds,
100,
20,
storageConfig.Name
);
cacheSettings.CacheManagers.Add(cacheManagerData);
cacheSettings.DefaultCacheManager = cacheManagerData.Name;
CacheManagerFactory cacheFactory = new CacheManagerFactory(configSource);
CacheManager = cacheFactory.CreateDefault();
}
catch (Exception e)
{
Console.WriteLine(e.Message);
}
}
public static T GetData<T>(string cacheKey)
{
var value = CacheManager.GetData(cacheKey);
return (T)value;
}
public static void AddData(string cacheKey, object value)
{
CacheManager.Add(cacheKey, value);
}
}
The issue is that the expirationPollFrequencyInSeconds
(here 2 seconds) is not taken into account when retrieving a cache item that is supposed to be expired. The item reside in cache longer than 2 seconds.
Any idea ?
See test example below:
private static void Main(string[] args)
{
try
{
LocalCache.AddData("One", 1);
Thread.Sleep(5000);
LocalCache.AddData("Two", 2);
object data = LocalCache.GetData<object>("One");
if (data == null) Console.WriteLine("Data not in cache");
else Console.WriteLine("-----> Data in cache whereas it should not !!!");
}
catch (Exception e)
{
Console.WriteLine(e.Message);
}
}
Output:
-----> Data in cache whereas it should not !!!
答案 0 :(得分:0)
根据CacheManagerData类的在线文档,构造函数不会占用缓存专家持续时间。相反,第二个参数是经理将检查如果项目太多,是否要删除缓存项目的时间段。
因此,2秒不是缓存到期。
是否有太多项目取决于第三个参数。
https://msdn.microsoft.com/en-us/library/ee779632.aspx
如果您想添加有效期,请查看以下内容: