.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();
}
```

posted @   jiftle  阅读(665)  评论(0编辑  收藏  举报
编辑推荐:
· 浏览器原生「磁吸」效果!Anchor Positioning 锚点定位神器解析
· 没有源码,如何修改代码逻辑?
· 一个奇形怪状的面试题:Bean中的CHM要不要加volatile?
· [.NET]调用本地 Deepseek 模型
· 一个费力不讨好的项目,让我损失了近一半的绩效!
阅读排行:
· 在鹅厂做java开发是什么体验
· 百万级群聊的设计实践
· WPF到Web的无缝过渡:英雄联盟客户端的OpenSilver迁移实战
· 永远不要相信用户的输入:从 SQL 注入攻防看输入验证的重要性
· 浏览器原生「磁吸」效果!Anchor Positioning 锚点定位神器解析
点击右上角即可分享
微信分享提示