http://www.cnblogs.com/kissdodog/archive/2013/05/07/3064895.html
using System.Web;
public sealed class Cache : IEnumerable{}
namespace ConsoleApplication1 { class Person { public int Id { get; set; } public string Name { get; set; } } class Program { static void Main(string[] args) { Person person = new Person { Id = 1, Name = "诸葛亮" }; Cache cache = HttpRuntime.Cache; /* //cache = HttpContext.Current.Cache; cache.Insert("AA",person); cache.Insert("BB","字符串"); Console.WriteLine(cache.Get("BB").ToString()); Person p = cache["AA"] as Person; if (p!=null) { Console.WriteLine(p.Id+","+p.Name); } Console.WriteLine(cache.EffectivePercentagePhysicalMemoryLimit); Console.WriteLine(cache.EffectivePrivateBytesLimit); Console.WriteLine(cache.Count); Console.WriteLine(cache["BB"]); cache.Remove("BB"); Console.WriteLine(cache["BB"]); foreach (var item in cache) { Console.WriteLine(item.GetType()+" "); } Console.WriteLine(""); cache.Insert("CC","依赖项测试",new CacheDependency(@"d:123.txt")); Console.WriteLine(cache["CC"]); //Console.ReadLine(); //Console.WriteLine(cache["CC"]); Console.ReadLine(); Console.WriteLine(cache["CC"]); cache.Insert("DD","绝对过期时间测试",null,DateTime.Now.AddSeconds(2),System.Web.Caching.Cache.NoSlidingExpiration); Console.WriteLine(cache["DD"]); //Thread.Sleep(3*1000); //Console.WriteLine(cache["DD"]); Thread.Sleep(2 * 1000); Console.WriteLine(cache["DD"]); cache.Insert("EE", "滑动过期时间", null, System.Web.Caching.Cache.NoAbsoluteExpiration, TimeSpan.FromSeconds(2)); Console.WriteLine(cache["EE"]); // Console.ReadLine(); //Thread.Sleep(4*1000); System.Diagnostics.Stopwatch sw = new System.Diagnostics.Stopwatch(); //sw.Start(); Console.WriteLine(cache["EE"]); Thread.Sleep(1*1000); Thread.Sleep(600); Console.WriteLine(cache["EE"]); //for (int i = 0; i < 5000; i++) //{ // Console.Write(i+","); //} //Console.WriteLine(); // sw.Stop(); //Console.WriteLine(sw.ElapsedMilliseconds); sw.Start(); Console.WriteLine(cache["EE"]); Thread.Sleep(1*1000); Thread.Sleep(600); sw.Stop(); Console.WriteLine(sw.ElapsedMilliseconds); Console.WriteLine(cache["EE"]);*/ cache.Add("MyData", "缓存移除通知", null, DateTime.Now.AddSeconds(2), Cache.NoSlidingExpiration, CacheItemPriority.Low, (string key, object value, CacheItemRemovedReason reson) => { Cache ca = HttpRuntime.Cache; ca.Insert("MyData", "缓存被清空了"); }); Console.WriteLine(cache["MyData"]); Thread.Sleep(2*1000); Console.WriteLine(cache["MyData"]); Console.ReadLine(); } } }