我什么都没找到,所以我不相信我想要的是可能的。我想在每次访问缓存变量时重置它的滑动过期时间。
public class MyCache
{
public static object CachedItem
{
get
{
string key = "item11"; // users share the object at this key
object o = Cache[key];
//re-set the timer janky way
//triggers callback, which I dont want
o = (o == null) ? new object() : Cache.Remove(key);
Cache.Add(key, o, null, Cache.NoAbs..., new TimeSpan(0,5,0), High, Removed);
return o;
}
}
private static void Removed(string key, object value, CacheItemRemovedReason reason)
{
// audit MySql table
// no good because Cache.Remove is getting called manually a lot.
}
}
在实践中,缓存项目是聊天室中的消息列表。当添加消息时,我希望聊天室能"活得更长"一点。替代方法也很受欢迎。
缓存对象在每次访问时都会自动重置过期时间。你所要做的就是尝试获取对象,如果它为null,则像现在一样设置滑动过期,如果不是null,则返回它。只需获取它,过期就会重置。像这样
public static object CachedItem
{
get
{
string key = "item11"; // users share the object at this key
object o = Cache[key];
if (o == null)
{
o = {Get from some source};
Cache.Add(key, o, null, Cache.NoAbs..., new TimeSpan(0,5,0), High, Removed);
}
return o;
}
}