.NET 4.0中的缓存功能
# .NET 4.0中的缓存功能
.Net 4.0中有3种,System.Runtime.Caching,System.Web.Caching.Cache,
Output.Cache。下面分别对这三者进行介绍:
### 应用程序缓存 System.Runtime.Caching
-----------------------------
.net4内置的高速缓存
```
private void button1_Click(object sender, EventArgs e)
{
ObjectCache objectCache = MemoryCache.Default;
string value1 = objectCache["key1"] as string;
CacheItemPolicy policy = new CacheItemPolicy();
//--------------设置过期时间----------------
policy.AbsoluteExpiration = DateTime.Now.AddHours(1);
objectCache.Set("key1", "11223366", policy);
value1 = objectCache["key1"] as string;
//---------------测试不同类型时 as 是否能自动转换---------
objectCache.Set("key1", 112233, policy);
value1 = objectCache["key1"] as string;
//---------------测试Add方法,在键已经存在的情况下会不会报错------
bool b = objectCache.Add("key1", 112233, policy);
//---------------测试Add方法,键不存在的情况------
b = objectCache.Add("key2", 445566, policy);
int n = (int)objectCache.Get("key2") ;
}
```
### Web应用程序缓存 System.Web.Caching.Cache
-----------------------------
Web程序的缓存,Asp.Net MVC4中使用ViewBag来传递参数。
```
public ActionResult CacheTest()
{
ViewBag.Message = "Web缓存";
Cache cache = HttpRuntime.Cache;
if (cache["Key1"] == null)
{
cache.Add("Key1", "Value 1", null, DateTime.Now.AddSeconds(600), Cache.NoSlidingExpiration, CacheItemPriority.High, onRemove);
}
`
string s = cache["Key1"] as string;
ViewBag.Key1 = s;
ViewBag.Setting = "配置啊";
return View();
}
//-----------------Razor页面使用-------------------
@ViewBag.Key1
```
### 页面输出缓存 Output.Cache
-----------------------------
页面输出缓冲,Output.Cache是MVC的一个注解[Output.Cache]。
在过期时间内,返回给浏览器304,表示页面内容未修改。
```
[OutputCache(Duration =20)]//设置过期时间为20秒
public ActionResult ExampleCache()
{
var timeStr =DateTime.Now.ToString("yyyy年MM月dd日 HH时mm分ss秒");
ViewBag.timeStr = timeStr;
return View();
}
```