指定單一過期時間點:
DateTime refreshTime = new DateTime(2005, 11, 12, 12, 51, 30);
AbsoluteTime expireTime = new AbsoluteTime(refreshTime);
IsolatedCacheManager.Add("MyDataSet", ds, CacheItemPriority.Normal, null, expireTime);
使用 Cron-like 運算式(格式:分 時 日 月 週):
// 每週六 00:00 過期
ExtendedFormatTime expireTime = new ExtendedFormatTime("0 0 * * 6");
IsolatedCacheManager.Add("Key1", "Cache Item1", CacheItemPriority.Normal, null, expireTime);
* * * * *:每分鐘5 * * * *:每小時第 5 分鐘* 21 * * *:每天 21:0031 15 * * *:每天 15:317 4 * * 6:週六 04:0715 21 4 7 *:7 月 4 日 21:15上次存取後經過指定間隔過期:
TimeSpan refreshTime = new TimeSpan(0, 5, 0); // 5 分鐘
SlidingTime expireTime = new SlidingTime(refreshTime);
IsolatedCacheManager.Add("Key1", "Cache Item1", CacheItemPriority.Normal, null, expireTime);
FileDependency expireNotice = new FileDependency("DependencyFile.txt");
myCacheManager.Add("FileKey", "String: Test Cache Item Dependency",
CacheItemPriority.Normal, null, expireNotice);
自訂過期類別需實作 ICacheItemExpiration 介面。
觸發時機:過期、明確移除、清除策略執行。實作 ICacheItemRefreshAction 介面,若需後端儲存須標記 [Serializable]:
[Serializable]
public class ProductCacheRefreshAction : ICacheItemRefreshAction
{
public void Refresh(string key, object expiredValue, CacheItemRemovedReason removalReason)
{
// 重新載入資料邏輯
}
}
應用程式啟動時預載。優點:執行期效能佳;缺點:啟動慢、可能浪費資源。適用:資料更新週期固定、生命週期明確、資源不穩定時。
CacheManager productsCache = CacheManager.GetCacheManager();
ArrayList list = dataProvider.GetProductList();
for (int i = 0; i < list.Count; i++)
{
Product product = (Product)list[i];
productsCache.Add(product.ProductID, product);
}
按需載入。優點:資源需求小;缺點:首次存取較慢。適用:狀態過多、資源不足、啟動期不想用快取。
CacheManager productsCache = CacheManager.GetCacheManager();
Product product = (Product)productsCache.GetData(productID);
if (product == null)
{
product = dataProvider.GetProductByID(productID);
if (product != null) productsCache.Add(productID, product);
}
程式碼主動呼叫,可移除全部或特定項目。
由區塊依優先級與最後存取時間自動執行。組態設定:
MaximumElementsInCacheBeforeScavenging:觸發清除的最大項目數NumberToRemoveWhenScavenging:每次清除項目數for (int intCount = 0; intCount < 8; intCount++)
{
string strKeyName = "Key" + intCount;
if (intCount % 2 == 0)
myCacheManager.Add(strKeyName, "High", CacheItemPriority.High, null, null);
else
myCacheManager.Add(strKeyName, "Low", CacheItemPriority.Low, null, null);
}
優先級:Low、Normal、High、NotRemovable。