寻找一个非常简单的缓存示例

编程入门 行业动态 更新时间:2024-10-11 13:30:34
本文介绍了寻找一个非常简单的缓存示例的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我正在寻找一个有关如何添加对象以缓存,再次取回并删除它的简单示例.

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 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 -此类可以用用户代码构造.它具有不同的界面和更多功能,如update \ remove回调,区域,监视器等.要使用它,您需要导入库System.Runtime.Caching.它也可以在ASP应用程序中使用,但是您必须自己管理其生命周期.

  • 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 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

  • 更多推荐

    寻找一个非常简单的缓存示例

    本文发布于:2023-11-10 07:10:07,感谢您对本站的认可!
    本文链接:https://www.elefans.com/category/jswz/34/1574697.html
    版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
    本文标签:示例   缓存   简单

    发布评论

    评论列表 (有 0 条评论)
    草根站长

    >www.elefans.com

    编程频道|电子爱好者 - 技术资讯及电子产品介绍!