C# System.Runtime.Caching使用

时间:2021-11-04 08:23:17

System.Runtime.Caching命名空间是.NET 4.0新增的,目的是将以前的.NET 版本中的System.Web.Caching单独提取出来,独立使用,这样web和其他.NET程序如WPF都可以使用。

System.Runtime.Caching包含缓存类和监视类,,包括文件、数据库、缓存等的监视,与以前在System.Web.Caching中的一样,但重新包装。

可以预见在以后的版本中,System.Web.Caching命名空间会被标记为Obsolete(过时),或者重写为包装System.Runtime.Caching中的方法。

using System.Runtime.Caching;

public static string GetToken() { ObjectCache oCache = MemoryCache.Default; string fileContents = oCache["wechart_token"] as string; if (fileContents == null) { CacheItemPolicy policy = new CacheItemPolicy(); policy.AbsoluteExpiration = DateTime.Now.AddMinutes(120);//取得或设定值,这个值会指定是否应该在指定期间过后清除 fileContents = //这里赋值; oCache.Set("wechart_token", fileContents, policy); } return fileContents; }