Looking for a very simple Cache example

前端 未结 5 1962
没有蜡笔的小新
没有蜡笔的小新 2020-12-13 13:51

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 lov

5条回答
  •  轮回少年
    2020-12-13 14:27

    .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 list = new List();
      
          HttpContext.Cache["ObjectList"] = list;                 // add
          list = (List)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)cache["ObjectList"]; // retrieve
      cache.Remove("ObjectList");                 // remove
      
      
          

      提交回复
      热议问题