博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
.NET 4.0中的缓存功能
阅读量:4564 次
发布时间:2019-06-08

本文共 1808 字,大约阅读时间需要 6 分钟。

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

转载于:https://www.cnblogs.com/jiftle/p/7760363.html

你可能感兴趣的文章
Lua学习笔记
查看>>
Redis监控工具,命令和调优
查看>>
zabbix-mysql迁移分离
查看>>
jQuery调用WCF 说明
查看>>
算法第5章作业
查看>>
7.9 练习
查看>>
基于ArcGIS JS API的在线专题地图实现
查看>>
learnByWork
查看>>
Unity3D热更新之LuaFramework篇[04]--自定义UI监听方法
查看>>
lua 函数
查看>>
Git的基本命令
查看>>
四平方和
查看>>
第十八周 12.27-1.2
查看>>
C# IP地址字符串和数值转换
查看>>
TCHAR和CHAR类型的互转
查看>>
常用界面布局
查看>>
C语言—— for 循环
查看>>
IBM lotus9.0测试版即将公测
查看>>
xml常用方法
查看>>
Cube Stacking(并差集深度+结点个数)
查看>>