Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
301 views
in Technique[技术] by (71.8m points)

c# - Looking for a very simple Cache example

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

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

1 Reply

0 votes
by (71.8m points)

.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
    

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...