C# MemoryCache 类[转载]

原网址:http://www.cmono.net/post/read/156

MemoryCache 类是.Net 4.0推出的类库,主要是为了方便在Winform和Wpf中构建缓存框架的
ObjectCache cache = MemoryCache.Default;    //得到MemoryCache全局实例
string myData = cache["mydata"] as string;  //访问缓存数据

if (myData == null)
{
    CacheItemPolicy policy = new CacheItemPolicy();  //创建缓存项策略

    //过期时间设置,以下两种只能设置一种
    policy.AbsoluteExpiration = new DateTimeOffset(DateTime.Now.AddMinutes(5)); //设定某个时间过后将逐出缓存
    policy.SlidingExpiration = new TimeSpan(0, 0, 10);    //设定某个时间段内未被访问将逐出缓存

    //逐出通知,以下两种只能设置一种
    policy.UpdateCallback = arguments => { Console.WriteLine("即将逐出缓存" + arguments.Key); };  //逐出前执行的方法
    //policy.RemovedCallback = arguments => { Console.WriteLine("已经逐出缓存" + arguments.CacheItem.Key); };  //逐出后执行的方法

    //缓存监视类有4种
    //CacheEntryChangeMonitor;
    //FileChangeMonitor;
    //HostFileChangeMonitor;
    //SqlChangeMonitor;
    //用法
    //List<string> filePaths = new List<string>();
    //filePaths.Add("c:\cache\example.txt");
    //policy.ChangeMonitors.Add(new HostFileChangeMonitor(filePaths));
    myData = "缓存数据"+DateTime.Now.ToShortTimeString();

     cache.Set("mydata", myData, policy);  //设置缓存数据,如果已存在则覆盖
}

Console.WriteLine("得到" + myData);

《C# MemoryCache 类》 由 常伟华 创作。 
本作品采用知识共享署名-相同方式共享 4.0 国际许可协议进行许可。 

原文地址:https://www.cnblogs.com/wenjie/p/5549764.html