简单的C#ASP.NET缓存实现

时间:2010-03-16 21:15:42

标签: c# asp.net caching

我需要构建一个List<object>并缓存列表并能够附加到它。我还需要能够轻松地将其吹走并重新创建它。什么是实现这一目标的简单方法?

3 个答案:

答案 0 :(得分:17)

或许这样的事情?

using System;
using System.Collections.Generic;
using System.Web;

public class MyListCache
{
    private List<object> _MyList = null;
    public List<object> MyList {
        get {
            if (_MyList == null) {
                _MyList = (HttpContext.Current.Cache["MyList"] as List<object>);
                if (_MyList == null) {
                    _MyList = new List<object>();
                    HttpContext.Current.Cache.Insert("MyList", _MyList);
                }
            }
            return _MyList;
        }
        set {
            HttpContext.Current.Cache.Insert("MyList", _MyList);
        }
    }

    public void ClearList() {
        HttpContext.Current.Cache.Remove("MyList");
    }
}

关于如何使用.....

// Get an instance
var listCache = new MyListCache();

// Add something
listCache.MyList.Add(someObject);

// Enumerate
foreach(var o in listCache.MyList) {
  Console.WriteLine(o.ToString());
}  

// Blow it away
listCache.ClearList();

答案 1 :(得分:2)

本教程是我发现的有用的

这是一个示例

List<object> list = new List<Object>();

Cache["ObjectList"] = list;                 // add
list = ( List<object>) Cache["ObjectList"]; // retrieve
Cache.Remove("ObjectList");                 // remove

答案 2 :(得分:0)

"Tracing and Caching Provider Wrappers for Entity Framework"的缓存部分虽然不简单,但仍然可以很好地回顾一些有待缓存的有用内容。

具体来说,两个类InMemoryCacheAspNetCache及其相关测试:

与问题类似,您可以将HttpRuntime.CacheHttpContext.Current.ItemsHttpContext.Current.Cache包含在ICache的实现中。