【发布时间】:2011-01-28 07:54:13
【问题描述】:
我需要建立一个List<object> 并缓存列表并能够附加到它。我还需要能够轻松地将其吹走并重新创建它。有什么简单的方法可以做到这一点?
【问题讨论】:
-
请记住,您的 List 不是线程安全的。
我需要建立一个List<object> 并缓存列表并能够附加到它。我还需要能够轻松地将其吹走并重新创建它。有什么简单的方法可以做到这一点?
【问题讨论】:
大概是这样的吧?
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();
【讨论】:
本教程对我很有帮助
这是一个示例
List<object> list = new List<Object>();
Cache["ObjectList"] = list; // add
list = ( List<object>) Cache["ObjectList"]; // retrieve
Cache.Remove("ObjectList"); // remove
【讨论】:
"Tracing and Caching Provider Wrappers for Entity Framework" 的缓存部分虽然不简单,但仍然很好地回顾了一些关于缓存的有用问题。
具体来说,InMemoryCache 和 AspNetCache 这两个类及其相关测试:
与问题的作用类似,您可以将HttpRuntime.Cache 或HttpContext.Current.Items 或HttpContext.Current.Cache 包装在ICache 的实现中。
【讨论】: