Here is my code:
public class ConfigCache
{
private static volatile ObjectCache _cache = MemoryCache.Default;
private const string KeyModule = "MODULE_XDOC_KEY";
private static string _settingFile;
public ConfigCache(string file)
{
_settingFile = file;
}
public XDocument Get()
{
var doc = _cache[KeyModule] as XDocument;
if (doc == null)
{
doc = XDocument.Load(_settingFile);
var policy = new CacheItemPolicy();
var filePaths = new List<string> {_settingFile};
policy.ChangeMonitors.Add(new HostFileChangeMonitor(filePaths));
var callback = new CacheEntryRemovedCallback(this.MyCachedItemRemovedCallback);
policy.RemovedCallback = callback;
_cache.Set(KeyModule, doc, policy);
}
return _cache[KeyModule] as XDocument;
}
private void MyCachedItemRemovedCallback(CacheEntryRemovedArguments arguments)
{
// Log these values from arguments list
}
}
When run into _cache.Set() first time, it works fine:
- _cache.Set() works well, it add the xdoc into cache.
But after several minutes(1 or 2 minutes), cache will not work anymore:
- _cache.Set() does not insert anything into cache
- _cache.Set() does not report any error.
- the callback MyCachedItemRemovedCallback never triggered.
Someone met same issue: MemoryCache always returns "null" after first expiration
But it seems not resolved yet. Anyone have any idea on this?