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

问题描述 投票:2回答:1

.Net Core中是否有CacheDependency类?似乎还没有实现。 我们有替代或解决方法吗?或者是否有关于此课程实施的未来计划? 这是.net框架支持的非常有用的功能,如何在没有它的情况下在缓存和文件之间建立依赖关系?

caching asp.net-core .net-core asp.net-core-2.0 .net-standard
1个回答
3
投票

您应该能够使用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找到。

© www.soinside.com 2019 - 2024. All rights reserved.