39

I'm looking for a real simple example of how to add an object to cache, get it back out again, and remove it.

The second answer here is the kind of example I'd love to see...

List<object> list = new List<Object>();

Cache["ObjectList"] = list;                 // add
list = ( List<object>) Cache["ObjectList"]; // retrieve
Cache.Remove("ObjectList");                 // remove

But when I try this, on the first line I get:

'Cache' is a type, which is not valid in the given context.

And on the third line I get:

An object method is required for the non-static field blah blah blah

So, let's say I have a List<T>...

var myList = GetListFromDB()

And now I just wanna add myList to the cache, get it back out, and remove it.

0

5 Answers 5

34

.NET provides a few Cache classes

  • System.Web.Caching.Cache - default caching mechanizm in ASP.NET. You can get instance of this class via property Controller.HttpContext.Cache also you can get it via singleton HttpContext.Current.Cache. This class is not expected to be created explicitly because under the hood it uses another caching engine that is assigned internally. To make your code work the simplest way is to do the following:

    public class AccountController : System.Web.Mvc.Controller{ 
      public System.Web.Mvc.ActionResult Index(){
        List<object> list = new List<Object>();
    
        HttpContext.Cache["ObjectList"] = list;                 // add
        list = (List<object>)HttpContext.Cache["ObjectList"]; // retrieve
        HttpContext.Cache.Remove("ObjectList");                 // remove
        return new System.Web.Mvc.EmptyResult();
      }
    }
    
  • System.Runtime.Caching.MemoryCache - this class can be constructed in user code. It has the different interface and more features like update\remove callbacks, regions, monitors etc. To use it you need to import library System.Runtime.Caching. It can be also used in ASP.net application, but you will have to manage its lifetime by yourself.

    var cache = new System.Runtime.Caching.MemoryCache("MyTestCache");
    cache["ObjectList"] = list;                 // add
    list = (List<object>)cache["ObjectList"]; // retrieve
    cache.Remove("ObjectList");                 // remove
    
2
20

Here is the way that I've done it in the past:

     private static string _key = "foo";
     private static readonly MemoryCache _cache = MemoryCache.Default;

     //Store Stuff in the cache  
   public static void StoreItemsInCache()
   {
      List<string> itemsToAdd = new List<string>();

      //Do what you need to do here. Database Interaction, Serialization,etc.
       var cacheItemPolicy = new CacheItemPolicy()
       {
         //Set your Cache expiration.
         AbsoluteExpiration = DateTime.Now.AddDays(1)
        };
         //remember to use the above created object as third parameter.
       _cache.Add(_key, itemsToAdd, cacheItemPolicy);
    }

    //Get stuff from the cache
    public static List<string> GetItemsFromCache()
    {
      if (!_cache.Contains(_key))
               StoreItemsInCache();

        return _cache.Get(_key) as List<string>;
    }

    //Remove stuff from the cache. If no key supplied, all data will be erased.
    public static void RemoveItemsFromCache(_key)
    {
      if (string.IsNullOrEmpty(_key))
        {
            _cache.Dispose();
        }
        else
        {
            _cache.Remove(_key);
        }
    }

EDIT: Formatting.

BTW, you can do this with anything. I used this in conjunction with serialization to store and retrieve a 150K item List of objects.

1
  • 1
    Nice example, just a minor change - this line should be Lower Camel Case: _cache.Add(_key, itemsToAdd, cacheItemPolicy); Commented Aug 2, 2018 at 21:52
13

If your using MemoryCache here is a very simple example:

var cache = MemoryCache.Default;

var key = "myKey";
var value = "my value";
var policy = new CacheItemPolicy { SlidingExpiration = new TimeSpan(2, 0, 0) };
cache.Add(key, value, policy);

Console.Write(cache[key]);
8

I wrote LazyCache to make this as simple and painless as possible, while also making sure you only execute your cacheable function calls once, even if two threads try and cache them at the same time.

Run the following command in the Package Manager Console

PM> Install-Package LazyCache

Add the namespace at the top of you class

using LazyCache;

and now cache stuff:

// Create the cache - (in constructor or using dependency injection)
IAppCache cache = new CachingService();

// Get products from the cache, or if they are not
// cached then get from db and cache them, in one line
var products = cache.GetOrAdd("get-products", () => dbContext.Products.ToList());

// later if you want to remove them
cache.Remove("get-products");

See more on the cache aside pattern or in the the LazyCache docs

1
  • Nice nuget package, thanks
    – geedubb
    Commented Sep 21, 2022 at 14:20
2

Try this third party cache: CacheCrow, it is a simple LFU based cache.

Install using powershell command in visual studio: Install-Package CacheCrow

Code Snippet:

 // initialization of singleton class
    ICacheCrow<string, string> cache = CacheCrow<string, string>.Initialize(1000);

    // adding value to cache
    cache.Add("#12","Jack");

    // searching value in cache
    var flag = cache.LookUp("#12");
    if(flag)
    {
        Console.WriteLine("Found");
    }

    // removing value
    var value = cache.Remove("#12");

For more information you can visit: https://github.com/RishabKumar/CacheCrow

Not the answer you're looking for? Browse other questions tagged or ask your own question.