代码之家  ›  专栏  ›  技术社区  ›  Jay Shah

中的CacheDependency类。Net Core在缓存和文件之间建立依赖关系

  •  4
  • Jay Shah  · 技术社区  · 7 年前

    中是否存在CacheDependency类。净核心?这似乎还没有实现。

    我们是否有任何替代或解决方法?或者对于这个类的实现是否有任何未来的计划?

    这是中支持的非常有用的功能。net framework,如果没有它,我如何在缓存和文件之间建立依赖关系?

    1 回复  |  直到 7 年前
        1
  •  9
  •   Marian Polacek    6 年前

    您应该能够使用 ChangeToken 实现类似于CacheDependency的功能。您必须使用其中一个文件提供程序才能获取的实例 IChangeToken . 然后可以将此令牌用作缓存的参数。

    非常基本的示例:

    IMemoryCache cache = GetCache();
    string fileContent = GetFileContent("sample.txt");
    
    // instance of file provider should be ideally taken from IOC container
    var fileProvider = new PhysicalFileProvider(Directory.GetCurrentDirectory()); 
    
    IChangeToken token = _fileProvider.Watch("sample.txt");
    
    // file will be removed from cache only if it is changed
    var cacheEntryOptions = new MemoryCacheEntryOptions()
                .AddExpirationToken(changeToken);
    
    // put file content into cache 
    cache.Set("sample.txt", fileContent, cacheEntryOptions);
    

    详细说明请参见 microsoft documentation for change tokens .