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

我需要建立一个List并缓存列表并能够附加到它。 我还需要能够轻松地将其吹走并重新创建它。 有什么简单的方法可以做到这一点?

也许这样的事情?

 using System; using System.Collections.Generic; using System.Web; public class MyListCache { private List _MyList = null; public List MyList { get { if (_MyList == null) { _MyList = (HttpContext.Current.Cache["MyList"] as List); if (_MyList == null) { _MyList = new List(); 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(); 

本教程是我发现有用的

  • ASP.NET缓存function

这是一个样本

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

“entity framework的跟踪和缓存提供程序包装器”的缓存部分虽然不简单,但仍然可以很好地回顾一些有待缓存的有用事项。

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

  • ICACHE
  • InMemoryCache和测试
  • AspNetCache

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