.NET Caching how does Sliding Expiration work?

2020-02-24 06:15发布

If I use an ObjectCache and add an item like so:

ObjectCache cache = MemoryCache.Default;
string o = "mydata";
cache.Add("mykey", o, DateTime.Now.AddDays(1));

I understand the object will expire in 1 day. But if the object is accessed 1/2 a day later using:

object mystuff = cache["mykey"];

Does this reset the timer so it's now 1 day since the last access of the entry with the key "mykey", or it still 1/2 a day until expiry?

If the answer is no and there is a way to do this I would love to know.

Thanks.

标签: c# .net caching
2条回答
兄弟一词,经得起流年.
2楼-- · 2020-02-24 06:49

The SlidingExpiration property value is set using the slidingExpiration attribute of the configuration element. Sliding expiration resets the expiration time for a valid authentication cookie if a request is made and more than half of the timeout interval has elapsed. If the cookie expires, the user must re-authenticate. Setting the SlidingExpiration property to false can improve the security of an application by limiting the time for which an authentication cookie is valid, based on the configured timeout value. We recommend that if you configure requireSSL as false, you also configure slidingExpiration as false, to reduce the amount of time for which a ticket is valid.

查看更多
forever°为你锁心
3楼-- · 2020-02-24 07:04

There are two types of cache policies you can use:

CacheItemPolicy.AbsoluteExpiration will expire the entry after a set amount of time.

CacheItemPolicy.SlidingExpiration will expire the entry if it hasn't been accessed in a set amount of time.

The ObjectCache Add() overload you're using treats it as an absolute expiration, which means it'll expire after 1 day, regardless of how many times you access it. You'll need to use one of the other overloads. Here's how you'd set a sliding expiration (it's a bit more complicated):

CacheItem item = cache.GetCacheItem("item");

if (item == null) {

    CacheItemPolicy policy = new CacheItemPolicy {
        SlidingExpiration = TimeSpan.FromDays(1)
    }

    item = new CacheItem("item", someData);

    cache.Set(item, policy);
}

You change the TimeSpan to the appropriate cache time that you want.

查看更多
登录 后发表回答