向缓存添加对象(Windows Server AppFabric 缓存)

以下示例显示向缓存添加对象的方法。

有关这些示例中使用的方法的详细信息,请按照这些链接查看类库主题:

备注

这些步骤假设您已设置缓存群集并且已准备好开发环境。有关详细信息,请参阅准备缓存客户端开发环境(Windows Server AppFabric 缓存)

向缓存添加对象

  1. 确保 using 语句(在 Visual Basic 中为 Imports)位于应用程序代码的顶部以引用 Microsoft.ApplicationServer.Caching 命名空间。

  2. 创建需要缓存客户端的应用程序的所有部分均可访问的 DataCacheFactory 对象。如有可能,存储并重复使用同一 DataCacheFactory 对象以节省内存并优化性能。

  3. 使用 DataCacheFactory 对象创建 DataCache 对象(也称为缓存客户端)。

  4. 在您拥有 DataCache 对象之后,使用 Add 方法、Put 方法或 Item 属性向缓存添加对象。在以下示例中,DataCache 实例命名为 myCache

示例

以下示例显示如何使用 Add 方法向缓存添加对象。如果同一密钥(首个参数)已经对对象进行了缓存,则将遇到异常。

'add string object to cache with key "Key0"
myCache.Add("Key0", "object added with Key0")
//add string object to cache with key "Key0"
myCache.Add("Key0", "object added with Key0");

以下示例使用 Put 方法向缓存添加对象。如果同一密钥已经对对象进行了缓存,则将替换该对象。

'add or replace string object in cache using key "Key0"
myCache.Put("Key0", "object replaced or added using Key0")
//add or replace string object in cache using key "Key0"
myCache.Put("Key0", "object replaced or added using Key0");

以下示例使用具有数组表示法的 Item 属性向缓存添加项目。如果同一密钥已经对对象进行了缓存,则将替换该对象。

'add or replace object in cache using array notation
myCache("Key0") = "object replaced or added using Key0"
//add or replace object in cache using array notation
myCache["Key0"] = "object replaced or added using Key0";

备注

许多其他参数均可用于 AddPut 方法。有关详细信息,请参阅 DataCache 类。

另请参阅

概念

准备缓存客户端开发环境(Windows Server AppFabric 缓存)
更新缓存中的对象(Windows Server AppFabric 缓存)
获取缓存中的对象(Windows Server AppFabric 缓存)
从缓存删除对象(Windows Server AppFabric 缓存)
Windows Server AppFabric 缓存概念
开发缓存客户端(Windows Server AppFabric 缓存)

  2011-12-05