`HttpRuntime.Cache` (或 `HttpContext.Current.Cache`) 提供應用程式層級快取,跨所有 Session 共享、支援過期策略、相依性與移除回呼。本類別提供簡潔的 `Write/Read/Remove` 介面。
using System;
using System.Web;
using System.Web.Caching;
public static class CacheHandler
{
/// 寫入快取,永不過期 (需手動移除)
public static bool Write(string cacheID, object data)
{
if (HttpContext.Current == null) return false;
if (String.IsNullOrEmpty(cacheID)) return false;
HttpRuntime.Cache.Insert(
cacheID, data, null,
Cache.NoAbsoluteExpiration, Cache.NoSlidingExpiration,
CacheItemPriority.NotRemovable, null);
return true;
}
/// 讀取快取
public static object Read(string cacheID)
{
if (HttpContext.Current == null) return null;
return HttpRuntime.Cache.Get(cacheID);
}
/// 移除快取
public static void Remove(string cacheID)
{
if (HttpContext.Current == null) return;
if (String.IsNullOrEmpty(cacheID)) return;
HttpRuntime.Cache.Remove(cacheID);
}
}
// 寫入:以 Session 專屬 Key 避免衝突
string cacheKey = "UserMenu_" + Session.SessionID;
CacheHandler.Write(cacheKey, menuData);
// 讀取
var menu = (List
public static bool Write(string cacheID, object data,
TimeSpan? slidingExpiration = null,
DateTime? absoluteExpiration = null,
CacheDependency dependency = null)
{
if (HttpContext.Current == null || String.IsNullOrEmpty(cacheID)) return false;
HttpRuntime.Cache.Insert(cacheID, data, dependency,
absoluteExpiration ?? Cache.NoAbsoluteExpiration,
slidingExpiration ?? Cache.NoSlidingExpiration,
CacheItemPriority.Normal, null);
return true;
}
// 使用:10 分鐘滑動過期
CacheHandler.Write("HotProducts", products, slidingExpiration: TimeSpan.FromMinutes(10));
// 使用:檔案相依性 (檔案變更自動失效)
var dep = new CacheDependency(Server.MapPath("~/Config/products.xml"));
CacheHandler.Write("ProductConfig", config, dependency: dep);
| 特性 | Cache | Session | Application |
|---|---|---|---|
| 共享範圍 | 全應用程式 | 單一用戶 | 全應用程式 |
| 過期策略 | 豐富 (絕對/滑動/相依) | 逾時移除 | 無 (手動清除) |
| 記憶體壓力管理 | 自動淘汰 (Priority) | 無 | 無 |
| 移除回呼 | 支援 | 不支援 | 不支援 |
| 執行緒安全 | 是 | 是 | 需 Lock |
最佳實務: 唯讀/高頻讀取資料 → Cache (設定 SlidingExpiration);用戶私有狀態 → Session;全站單一實例設定 → Application/Configuration;分散式環境 → Redis/IDistributedCache。