0

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?

Community
  • 1
  • 1

1 Answers1

0

Your problem might be that the cache is being disposed. This will result in the MemoryCache silently returning null rather than throwing any exception. First search your code to be sure you are not disposing it. If you are sure you aren't disposing it, try breaking on the AppDomain.UnhandledException event. MemoryCache subscribes to this event (see this answer and disposes itself. If you are handling the UnhandledException event in your app as a global error handler, this could be the problem.

If this is the issue, a simple workaround is to handle the event and recreate a new instance of the cache. (See my answer here)

Community
  • 1
  • 1
mao47
  • 967
  • 10
  • 25