可以使用 Cache 可以使用 Cache 对象的 Insert 该方法向缓存添加项,并且通过几次重载,您可以用不同选项添加项,以设置依赖项、过期和移除通知。如果使用 Insert
还可以使用 Add 使用此方法,您可以设置与 Insert 方法相同的所有选项;然而,Add 另外,如果使用 Add
本主题中的过程阐释了向应用程序缓存添加项的如下方式:
- 通过键和值直接设置项,向缓存添加项。
- 使用Insert
- 向缓存添加项并添加依赖项,以便当该依赖项更改时,将该项从缓存中移除。 可以基于其他缓存项、文件和多个对象设置依赖项。
- 将设有过期策略的项添加到缓存中。 除了能设置项的依赖项以外,还可以设置项在一段时间以后(弹性过期)或在指定时间(绝对过期)过期。 您可以定义绝对过期时间或弹性过期时间,但不能同时定义两者。
- 向缓存添加项,并定义缓存的项的相对优先级。 相对优先级帮助 .NET Framework 确定要移除的缓存项;较低优先级的项比较高优先级的项先从缓存中移除。
- 通过调用Add
除了这里显示的依赖项,可以在 SQL Server 表上或基于自定义依赖项创建依赖项。 有关更多信息,请参见 ASP.NET 缓存概述 和 使用 SqlCacheDependency 类在 ASP.NET 中缓存。
当从缓存中移除项时,还可以使用 CacheItemRemovedCallback 有关完整示例,请参见 如何:从缓存中移除项时通知应用程序。
通过键和值直接设置项向缓存添加项
- 通过指定项的键和值,像将项添加到字典中一样将其添加到缓存中。
下面的代码示例将名为 CacheItem1 的项添加到Cache
C#
Cache["CacheItem1"] = "Cached Item 1";
通过使用 Insert 方法将项添加到缓存中
- 调用Insert下面的代码示例添加名为 CacheItem2
C#
Cache.Insert("CacheItem2", "Cached Item 2");
通过指定依赖项向缓存添加项
- 调用Insert 方法,将 CacheDependency下面的代码示例添加名为 CacheItem3 的项,该项依赖于缓存中名为 CacheItem2
C#
string[] dependencies = { "CacheItem2" };
Cache.Insert("CacheItem3", "Cached Item 3",
new System.Web.Caching.CacheDependency(null, dependencies));
下面的代码示例演示将名为 CacheItem4
C#
Cache.Insert("CacheItem4", "Cached Item 4",
new System.Web.Caching.CacheDependency(
Server.MapPath("XMLFile.xml")));
下面的代码示例演示如何创建多个依赖项。 它向缓存中名为 CacheItem1
C#
System.Web.Caching.CacheDependency dep1 =
new System.Web.Caching.CacheDependency(Server.MapPath("XMLFile.xml"));
string[] keyDependencies2 = { "CacheItem1" };
System.Web.Caching.CacheDependency dep2 =
new System.Web.Caching.CacheDependency(null, keyDependencies2);
System.Web.Caching.AggregateCacheDependency aggDep =
new System.Web.Caching.AggregateCacheDependency();
aggDep.Add(dep1);
aggDep.Add(dep2);
Cache.Insert("CacheItem5", "Cached Item 5", aggDep);
将设有过期策略的项添加到缓存中
- 调用Insert下面的代码示例将有一分钟绝对过期时间的项添加到缓存中:
C#
Cache.Insert("CacheItem6", "Cached Item 6",
null, DateTime.Now.AddMinutes(1d),
System.Web.Caching.Cache.NoSlidingExpiration);
下面的代码示例将有 10 分钟弹性过期时间的项添加到缓存中:
C#
Cache.Insert("CacheItem7", "Cached Item 7",
null, System.Web.Caching.Cache.NoAbsoluteExpiration,
new
将设有优先级设置的项添加到缓存中
- 调用Insert 方法,从 CacheItemPriority下面的代码示例将优先级值为 High
C#
Cache.Insert("CacheItem8", "Cached Item 8",
null, System.Web.Caching.Cache.NoAbsoluteExpiration,
System.Web.Caching.Cache.NoSlidingExpiration,
System.Web.Caching.CacheItemPriority.High, null);
使用 Add 方法向缓存添加项
- 调用Add下面的代码示例向缓存添加名为 CacheItem9 的项,同时将变量 CachedItem9
C#
string CachedItem9 = (string)Cache.Add("CacheItem9",
"Cached Item 9", null,
System.Web.Caching.Cache.NoAbsoluteExpiration,
System.Web.Caching.Cache.NoSlidingExpiration,
System.Web.Caching.CacheItemPriority.Default,
null);
请参见
任务
如何:从 ASP.NET 缓存中删除项
如何:从缓存中移除项时通知应用程序
如何:检索缓存项的值
概念
ASP.NET 缓存概述
缓存应用程序数据
使用 SqlCacheDependency 类在 ASP.NET 中缓存
原文:http://msdn.microsoft.com/zh-cn/library/18c1wd61.aspx
作者:沐雪
为之网-热爱软件编程 http://www.weizhi.cc/