[英]Simple Data Caching using Weak References in WCF
鑒於我有以下WCF服務:
class LookUpService
{
public List<County> GetCounties(string state)
{
var db = new LookUpRepository();
return db.GetCounties(state);
}
}
class County
{
public string StateCode{get;set;}
public string CountyName{get;set;}
public int CountyCode{get;set;}
}
使用弱引用(或任何其他方法)緩存州縣的最有效(或最佳)方法是什么,這樣我們就不必每次需要查找數據時都訪問數據庫。
請注意 ,我們將無權訪問HttpRuntime(和HttpContext)。
對於這種情況,您將要使用WeakReference
樣式的哈希表。 BCL中沒有可用的功能(直到4.0),但在線有多個可用的功能。 我將在此示例中使用以下內容
嘗試以下cdoe
class LookupService {
private WeakHashtable<string,List<Count>> _map = new WeakHashtable<string,List<County>>();
public List<County> GetCounties(string state) {
List<Count> found;
if ( !_map.TryGetValue(state, out found)) {
var db = new LookUpRepository();
found = db.GetCounties(state);
_map.Add(state,found);
}
return found;
}
}
如您所見,與使用普通Dictionary<TKey,TValue>
並沒有太大區別
為什么沒有訪問HttpRuntime的權限? 您不需要上下文。 您只需要上課。
您可以在非ASP.NET應用程序中使用System.Web.Caching ,而無需使用HttpContext。
另請參閱在WCF中緩存?
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.