Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 881
Casey Crookston Avatar asked Jan 16 '17 20:01

Casey Crookston


People also ask

What is cache in C# with example?

It is a type of memory that is relatively small but can be accessed very quickly. It essentially stores information that is likely to be used again. For example, web browsers typically use a cache to make web pages load faster by storing a copy of the webpage files locally, such as on your local computer.


1 Answers

.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 
like image 52
Yuriy Tseretyan Avatar answered Sep 20 '22 21:09

Yuriy Tseretyan