Looking for a very simple Cache example

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.


.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