0

I am trying to cache a string in my .net mvc application for 24 hours. I am having trouble finding a way to get the cache to expire. Currently I set the cache using

System.Runtime.Caching.MemoryCache.Default["activeKey"] = "success";

I use the cache by calling

var activeKey = System.Runtime.Caching.MemoryCache.Default["activeKey"];
if (activeKey != null && (string) activeKey == "success")
{
    return true;
}

However, I am unsure where to go from here as far as cache. I found docs for sliding and absolute cache, but am unsure exactly what to do.

Uwe Keim
  • 39,551
  • 56
  • 175
  • 291
TheDizzle
  • 1,534
  • 5
  • 33
  • 76
  • have you checked this : https://msdn.microsoft.com/en-us/library/aa478965.aspx?f=255&MSPPError=-2147217396 – Ehsan Sajjad Apr 03 '18 at 13:49
  • `class HackItCacheItem { public DateTime Created {get;set;} public string Value {get;set;} }` if DateTime.Now - Created > TimeSpan.FromDays(1) ... –  Apr 03 '18 at 13:50
  • I think you need to use `Add()`, it has an overload for CacheItemPolicy – maccettura Apr 03 '18 at 13:50
  • https://stackoverflow.com/questions/1434284/when-does-asp-net-remove-expired-cache-items –  Apr 03 '18 at 13:51

1 Answers1

2

The Add or AddOrGetExisting methods are the best you can get. They both have an argument to set the expiration (absoluteExpiration).

System.Runtime.Caching.MemoryCache.Default.Add(
    "activeKey",
    "success",
    new DateTimeOffset(DateTime.Now.AddDays(1))
)
Patrick Hofman
  • 153,850
  • 22
  • 249
  • 325