【问题标题】:Simple Data Caching using Weak References in WCF在 WCF 中使用弱引用进行简单数据缓存
【发布时间】:2010-04-02 17:44:59
【问题描述】:

鉴于我有以下 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)。

【问题讨论】:

    标签: c# wcf caching weak-references


    【解决方案1】:

    对于这种情况,您将需要使用 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&lt;TKey,TValue&gt; 没有太大区别

    【讨论】:

      【解决方案2】:

      为什么您无法访问 HttpRuntime?你不需要上下文。你只需要上课。

      您可以在非 ASP.NET 应用程序中use System.Web.Caching,而无需使用 HttpContext。

      另见Caching in WCF?

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2016-04-21
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多