將物件新增至快取
下列範例顯示將物件新增到快取的方法。
如需有關這些範例中使用之方法的詳細資訊,請依照下列連結檢視類別庫主題:
注意
這些程序假設您已設定快取叢集並準備好開發環境。如需詳細資訊,請參閱準備快取用戶端開發環境 (AppFabric 1.1 快取)。
將物件新增至快取
確定 using 陳述式 (在 Visual Basic 中是 Imports) 位於應用程式程式碼頂端,以參考 Microsoft.ApplicationServer.Caching 命名空間。
建立 DataCacheFactory 物件,以供需要快取用戶端之應用程式的所有組件存取。如果可能,請儲存並重複使用相同的 DataCacheFactory 物件,以節省記憶體並最佳化效能。
使用 DataCacheFactory 物件來建立 DataCache 物件 (亦稱為「快取用戶端」)。
建立 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";
注意
有許多其他參數可供 Add 與 Put 方法使用。如需詳細資訊,請參閱 DataCache 類別。
另請參閱
概念
準備快取用戶端開發環境 (AppFabric 1.1 快取)
更新快取中的物件
從快取取得物件
從快取移除物件
AppFabric 快取概念 (AppFabric 1.1 快取)
開發快取用戶端
2012-03-05