본문 바로가기
C#(CSharp)/Etc

C# memory cache logic

by swconsulting 2018. 5. 31.

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)
        };

       _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>;
    }

EDIT: Formatting.

BTW, you can do this with anything. I used this is 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




source  : https://stackoverflow.com/questions/41684213/looking-for-a-very-simple-cache-example?utm_medium=organic&utm_source=google_rich_qa&utm_campaign=google_rich_qa