MemoryCache几分钟后不工作

本文关键字:工作 几分钟 分钟 MemoryCache | 更新日期: 2023-09-27 18:13:41

下面是我的代码:

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 
    }
}

当第一次运行_cache.Set()时,它工作正常:

  • _cache.Set()工作得很好,它将xdoc添加到缓存中。

但几分钟后(1或2分钟),缓存将不再工作:

  • _cache.Set()不向cache中插入任何内容
  • _cache.Set()没有报错。
  • 回调MyCachedItemRemovedCallback从未触发。

有人遇到了同样的问题:MemoryCache总是返回"null";第一次过期后

但似乎还没有解决。有人对此有什么想法吗?

MemoryCache几分钟后不工作

您的问题可能是缓存正在被处理。这将导致MemoryCache静默地返回null,而不是抛出任何异常。首先搜索您的代码,以确保您没有处理它。如果您确定不处理它,请尝试打开AppDomain.UnhandledException事件。MemoryCache订阅此事件(参见此答案并自行处理)。如果你在应用程序中将UnhandledException事件作为全局错误处理程序来处理,这可能是问题所在。

如果是这个问题,一个简单的解决方法是处理该事件并重新创建缓存的新实例。