[英]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.