HttpContext.Cache过期

Mic*_*cah 33 asp.net caching

有没有办法指定HttpContext.Cache中的数据保存时间?

Joh*_*sch 33

您可以在第4个参数中指定它Cache.Add():

public Object Add(
    string key,
    Object value,
    CacheDependency dependencies,
    DateTime absoluteExpiration,  // After this DateTime, it will be removed from the cache
    TimeSpan slidingExpiration,
    CacheItemPriority priority,
    CacheItemRemovedCallback onRemoveCallback
)
Run Code Online (Sandbox Code Playgroud)

编辑:

如果通过索引器(即Cache["Key"])访问缓存,则调用的方法不会使用到期,并且会无限期地保留在缓存中.

以下是使用索引器时调用的代码:

public void Insert(string key, object value)
{
    this._cacheInternal.DoInsert(true, key, value, null, NoAbsoluteExpiration, NoSlidingExpiration, CacheItemPriority.Normal, null, true);
}
Run Code Online (Sandbox Code Playgroud)


Ant*_*nes 17

使用Cache.Add方法,例如: -

 HttpContext.Cache.Add("mykey", someObj, null, Cache.NoAbsoluteExpiration, new TimeSpan(0, 15, 0), CacheItemPriority.Normal, null);
Run Code Online (Sandbox Code Playgroud)

上述内容在最后一次访问后的15分钟内到期.或者,您可以将Cache.NoSlidingExpiration传递给此参数,并在上一个参数中使用特定的DateTime.