2012-04-09 50 views
0

我想創建和指向緩存。我需要知道如何從一個方法調用創建一個緩存鍵並將其插入到緩存中並返回值。這部分是否有可用的解決方案?我不需要完整的緩存解決方案緩存服務調用

感謝

回答

0

我以前用過的RealProxy對於這種類型的功能。我在我的博客文章中展示了一些示例; Intercepting method invocations using RealProxy

緩存代理的一個簡單示例,使用方法的哈希代碼(確保兩個具有相同參數的不同方法分別緩存)和參數。請注意,沒有處理out-parameters,只有返回值。 (如果你想改變它,你需要改變_cache來保存一個包含返回值和輸出參數的對象。)另外,這個實現沒有表單線程安全性。

public class CachingProxy<T> : ProxyBase<T> where T : class { 
    private readonly IDictionary<Int32, Object> _cache = new Dictionary<Int32, Object>(); 

    public CachingProxy(T instance) 
     : base(instance) { 
    } 

    protected override IMethodReturnMessage InvokeMethodCall(IMethodCallMessage msg) { 
     var cacheKey = GetMethodCallHashCode(msg); 

     Object result; 
     if (_cache.TryGetValue(cacheKey, out result)) 
      return new ReturnMessage(result, msg.Args, msg.ArgCount, msg.LogicalCallContext, msg); 

     var returnMessage = base.InvokeMethodCall(msg); 

     if (returnMessage.Exception == null) 
      _cache[cacheKey] = returnMessage.ReturnValue; 

     return returnMessage; 
    } 

    protected virtual Int32 GetMethodCallHashCode(IMethodCallMessage msg) { 
     var hash = msg.MethodBase.GetHashCode(); 

     foreach(var arg in msg.InArgs) { 
      var argHash = (arg != null) ? arg.GetHashCode() : 0; 
      hash = ((hash << 5) + hash)^argHash; 
     } 

     return hash; 
    } 
} 
+0

我想你沒有得到這個問題,我需要知道是否有解決方案來創建一個表示方法調用的緩存鍵(字符串)及其返回值。例如緩存SomeMethod(param1,param2),但尋找能夠緩存具有任意數量參數的任何方法的通用解決方案 – Ehsan 2012-04-09 11:17:01

+0

我已經添加了一個基於ProxyBase 類的緩存調用的示例CachingProxy 。 – sisve 2012-04-09 14:01:12

+0

基於MSDN文檔GetHashCode方法對於創建唯一的哈希鍵是不可靠的,如果我們說我們應該爲每個類型實現此方法,我認爲這也是一種不好的做法http://msdn.microsoft.com/zh-cn/ us/library/system.object.gethashcode.aspx第3行的備註部分 – Ehsan 2012-04-09 18:38:46