Jerry Lam
Jerry Lam

Reputation: 452

.Net System.Web.Caching expiration issues

Suppose I have a cache that will expired after one minute.

Cache.Insert("tryin", 0, null, DateTime.Now.AddSeconds(60), Cache.NoSlidingExpiration);

In every 5 second I have a timer to increase the cache velue by 1, but here comes the problem. If I use the following syntax to update the cache's value,

Cache["tryin"] = Convert.ToInt16(Cache["tryin"]) + 1;

It will overwrite the cache and create a Cache["tryin"] with NoSlidingExpiration and NoAbsoluteExpiration, but I want that cache to be expired after a minute. I also tried to use the following syntax,

Cache.Insert("tryin", Convert.ToInt16(Cache["tryin"]) + 1, null, DateTime.Now.AddSeconds(60), Cache.NoSlidingExpiration);

But in this case I will end up creating a cache that will expired after a minute in ever 5 seconds, which make it won't expired.

So I am looking for a method to update the Cache value without changing the cache Expiration time, Or to get the remaining expiration of the Cache so I can create another one based on the remaining expiration time.

Upvotes: 0

Views: 798

Answers (1)

Igor
Igor

Reputation: 15893

I think the problem here is in cached item being a value type. You can wrap your integer in a class:

public class ValueHolder
{
  public int Value = 0;
}

Cache.Insert("tryin", new ValueHolder(){Value = 0}, null, DateTime.Now.AddSeconds(60), Cache.NoSlidingExpiration);

then

ValueHolder vh = (ValueHolder)Cache["tryin"];
if (vh != null)
  vh.Value = vh.Value + 1;

Upvotes: 2

Related Questions