我正在嘗試實現基于ObjectCache的FileCache(https://github.com/acarteas/FileCache)。我正在嘗試檢查緩存對象是否存在,或者在需要時添加它并返回。但是,如果對象不存在,則不執行委托,并引發錯誤:[...]中的類型'myNamespace.Controllers.ListController + <> c__DisplayClass0_0'未標記為可序列化。我嘗試過的內容(簡體):private string generateString(int? Id){ return "String";}public ActionResult GetSomething(int? Id){ var cacheFilePath = $"{AppDomain.CurrentDomain.BaseDirectory}{"\\cache"}"; var cache = new FileCache(cacheFilePath, false, TimeSpan.FromSeconds(30)); if (purgeCache) cache.Remove($"CacheKey{Id}"); Func<string> createString = () => generateString(Id); var myString = (string) cache.AddOrGetExisting($"CacheKey{Id}", createString, new CacheItemPolicy() { AbsoluteExpiration = DateTimeOffset.Now.AddSeconds(30) }); return new JsonStringResult(myString);}好的,現在我嘗試用Serializable指定委托createString,但這不起作用。有人可以指出我正確的方向嗎?本質上我想要:-運行一條語句,返回generateString(123)的先前輸出;如果它不存在或已過期,則應重新生成它。
2 回答

隔江千里
TA貢獻1906條經驗 獲得超10個贊
由于的性質FileCache,我認為做到這一點的唯一合理方法是回退到通常的方法-檢查項目是否存在于緩存中,如果不存在,則添加它:
private static readonly _cacheLock = new object();
private static readonly FileCache _cache = new FileCache($"{AppDomain.CurrentDomain.BaseDirectory}{"\\cache"}", false, TimeSpan.FromSeconds(30));
/// ...
lock (_cacheLock) {
var myString = _cache.Get($"CacheKey{Id}");
if (myString == null) {
myString = generateString(Id);
_cache.Set($"CacheKey{Id}", myString, new CacheItemPolicy() { AbsoluteExpiration = DateTimeOffset.Now.AddSeconds(30) });
}
}
鎖定是必需的,因為FileCache這兩個對象都從同一文件進行寫入和讀取,并且從多個線程執行此操作永遠都不安全。
- 2 回答
- 0 關注
- 171 瀏覽
添加回答
舉報
0/150
提交
取消