寻找一个非常简单的缓存示例
我正在寻找一个有关如何添加对象以缓存,再次取回并删除它的简单示例.
I'm looking for a real simple example of how to add an object to cache, get it back out again, and remove it.
第二个答案此处是我所举的一种示例d喜欢看...
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.
在第三行我得到:
非静态字段blah blah要求对象方法
An object method is required for the non-static field blah blah blah
所以,假设我有一个List<T>
...
So, let's say I have a List<T>
...
var myList = GetListFromDB()
现在我只想将myList
添加到缓存中,将其取回,然后将其删除.
And now I just wanna add myList
to the cache, get it back out, and remove it.
.NET提供了一些缓存类
.NET provides a few Cache classes
-
System.Web.Caching.Cache -ASP.NET中的默认缓存机制.您可以通过属性
Controller.HttpContext.Cache
获取此类的实例,也可以通过单例HttpContext.Current.Cache
获取它.不应明确创建此类,因为它在后台使用了另一个内部分配的缓存引擎. 要使代码正常工作,最简单的方法是执行以下操作:
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 singletonHttpContext.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 -此类可以用用户代码构造.它具有不同的界面和更多功能,如update \ remove回调,区域,监视器等.要使用它,您需要导入库System.Runtime.Caching
.它也可以在ASP.net应用程序中使用,但是您必须自己管理其生命周期.
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