public class AccountController : System.Web.Mvc.Controller{
public System.Web.Mvc.ActionResult Index(){
List list = new List();
HttpContext.Cache["ObjectList"] = list; // add
list = (List)HttpContext.Cache["ObjectList"]; // retrieve
HttpContext.Cache.Remove("ObjectList"); // remove
return new System.Web.Mvc.EmptyResult();
}
}
private static string _key = "foo";
private static readonly MemoryCache _cache = MemoryCache.Default;
//Store Stuff in the cache
public static void StoreItemsInCache()
{
List itemsToAdd = new List();
//Do what you need to do here. Database Interaction, Serialization,etc.
var cacheItemPolicy = new CacheItemPolicy()
{
//Set your Cache expiration.
AbsoluteExpiration = DateTime.Now.AddDays(1)
};
//remember to use the above created object as third parameter.
_cache.Add(_key, itemsToAdd, cacheItemPolicy);
}
//Get stuff from the cache
public static List GetItemsFromCache()
{
if (!_cache.Contains(_key))
StoreItemsInCache();
return _cache.Get(_key) as List;
}
//Remove stuff from the cache. If no key supplied, all data will be erased.
public static void RemoveItemsFromCache(_key)
{
if (string.IsNullOrEmpty(_key))
{
_cache.Dispose();
}
else
{
_cache.Remove(_key);
}
}
编辑:格式化.
顺便说一句,你可以做任何事情.我使用它与序列化结合来存储和检索150K项目的对象列表.
3> Kelly..:
如果你在这里使用MemoryCache是一个非常简单的例子:
var cache = MemoryCache.Default;
var key = "myKey";
var value = "my value";
var policy = new CacheItemPolicy { SlidingExpiration = new TimeSpan(2, 0, 0) };
cache.Add(key, value, policy);
Console.Write(cache[key]);