使缓存对象在午夜过期

Joh*_*han 1 asp.net caching

我有以下代码:

var tempList = new BrandCollection();
            if (HttpContext.Current.Cache["cachedDeviceList"] == null)
            {
                tempList = Provider.GetDeviceData(info);
                HttpContext.Current.Cache.Insert(...);
            }
            else
            {
                tempList = 
            }
Run Code Online (Sandbox Code Playgroud)

Cache.Insert() 方法已重载,我可以在其中设置依赖项、滑动和绝对过期。我想让缓存在午夜过期。我怎么做?预先感谢!

Phi*_*ove 5

绝对过期是做到这一点的方法 - 它是“在绝对时间点过期”的简写,而不是“从现在起的二十分钟内”。因此,当您将项目放入缓存时,您需要计算午夜是什么时候,然后将其用作到期点,例如

var tempList = new BrandCollection(); 
if (HttpContext.Current.Cache["cachedDeviceList"] == null) 
{ 
    tempList = Provider.GetDeviceData(info); 

    // Find out when midnight will be by taking Today and adding a day to it
    DateTime expirationTime = DateTime.Today.AddDays(1)
    HttpContext.Current.Cache.Insert("cachedDeviceList", tempList, null, expirationTime, NoSlidingExpiration, CacheItemPriority.Normal, null); 
} 
else 
{
    ...
}
Run Code Online (Sandbox Code Playgroud)