Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
294 views
Welcome To Ask or Share your Answers For Others

1 Answer

.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 emove 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
    

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...