当我使用CacheItemPolicy with HostFileChangeMonitor时,更改的文件需要5-7毫秒的缓存时间才能删除项目
[TestMethod]
public void TestHostFileChangeMonitor()
{
var cachedFilePath = @"c:\temp\123.txt";
File.WriteAllText(cachedFilePath, "1111");
System.Runtime.Caching.ObjectCache cache = MemoryCache.Default;
string fileContents = cache["filecontents"] as string;
if (fileContents == null)
{
CacheItemPolicy policy = new CacheItemPolicy();
List<string> filePaths = new List<string>();
filePaths.Add(cachedFilePath);
policy.ChangeMonitors.Add(new
HostFileChangeMonitor(filePaths));
// Fetch the file contents.
fileContents = File.ReadAllText(cachedFilePath);
cache.Set("filecontents", fileContents, policy);
}
File.WriteAllText(cachedFilePath, "2222");
int sleepTime = 5;
Thread.Sleep(sleepTime);
string fileContents2 = cache["filecontents"] as string;
Assert.AreEqual("2222", File.ReadAllText(cachedFilePath));
Assert.IsNull(fileContents2);// the test past only if sleepTime > 5
}发布于 2020-06-24 23:33:40
我的解决方案是将设置到缓存的时间保存在缓存和读取检查File.GetLastWriteTime中
[TestMethod]
public void TestHostFileChangeMonitor1()
{
var cachedFilePath = @"c:\temp\123.txt";
File.WriteAllText(cachedFilePath, "1111");
System.Runtime.Caching.ObjectCache cache = MemoryCache.Default;
CashObj cashObj = cache["filecontents"] as CashObj;
if (cashObj == null || cashObj.addedTime < File.GetLastWriteTime(cachedFilePath))
{
CacheItemPolicy policy = new CacheItemPolicy();
List<string> filePaths = new List<string>();
filePaths.Add(cachedFilePath);
policy.ChangeMonitors.Add(new
HostFileChangeMonitor(filePaths));
// Fetch the file contents.
var fileContents = File.ReadAllText(cachedFilePath);
cache.Set("filecontents", new CashObj(fileContents), policy);
}
File.WriteAllText(cachedFilePath, "2222");
cashObj = cache["filecontents"] as CashObj;
Assert.AreEqual("2222", File.ReadAllText(cachedFilePath));
Assert.IsTrue(cashObj == null || cashObj.addedTime < File.GetLastWriteTime(cachedFilePath));
}
public class CashObj
{
public object data;
public DateTime addedTime;
public CashObj(object data)
{
this.data = data;
this.addedTime = DateTime.Now;
}
}发布于 2020-06-26 01:01:30
您可以等待项目逐出。例如,使用Microsoft.Extensions.Caching.Memory.MemoryCache,您可以使用下一种方法来完成此操作。
TaskCompletionSource<bool> tcs = new TaskCompletionSource<bool>();
string key = "key";
MemoryCache msCache = new MemoryCache(new MemoryCacheOptions());
msCache.Set(key, tcs, new MemoryCacheEntryOptions()
.RegisterPostEvictionCallback(
(object callbackKey, object callbackValue, EvictionReason reason, object state) =>
{
tcs.SetResult(true);
}));
Task evictionTask = tcs.Task;
msCache.Remove(key);
await evictionTask;同样,对于System.Runtime.MemoryCache,您可以使用CacheEntryRemovedCallback而不是RegisterPostEvictionCallback
https://stackoverflow.com/questions/62558721
复制相似问题