2013-08-18 37 views
0

我第一次使用Fody方法缓存(https://github.com/Dresel/MethodCache)。我可能做错了什么,因为下面的代码不起作用:Fody - 方法缓存

static void Main() 
{ 
    Console.WriteLine("Begin calc 1..."); 
    var v = calc(5); 
    Console.WriteLine("Begin calc 2..."); //it last the same as the first function call 
    v = calc(5); 
    Console.WriteLine("end calc 2..."); 
} 

[Cache] 
static int calc(int b) 
{ 
    Thread.Sleep(5000); 
    return b + 5; 
} 

我应该使用具有以下功能: 第一个电话:缓存参数作为键和返回值的值。 任何其他调用:if cache[arg1, arg2,...]存在没有完成函数返回缓存值? (使用缓存属性)

+0

为什么第二个函数调用与第一个函数调用不一样?你只是在睡觉线程,没有任何操作缓存在那里。 – Tarec

+0

好的,我应该怎样使用它:第一次调用:缓存作为键的arugments并返回值作为值。任何其他调用:如果缓存[arg1,arg2,...]存在,但没有完成函数返回缓存值? – dajuric

+0

据我所知,如果一个函数被缓存,它不应该被执行,但它的值应该从缓存中返回。我不明白为什么Thread.Sleep(..)不合适? – dajuric

回答

2

正如我已经在你的github问题中所述,静态方法缓存被添加到1.3.1中。

由于设计了MethodCache.Fody,因此还必须将Cache Getter添加到包含应缓存和实现Cache的方法的类中。您可以编写自己的缓存或使用适配器连接现有的缓存解决方案(请参阅文档https://github.com/Dresel/MethodCache)。

为您的样品的最小码(与基本字典高速缓存实现)是这样的:

namespace ConsoleApplication 
{ 
    using System; 
    using System.Collections.Generic; 
    using System.Threading; 
    using MethodCache.Attributes; 

    public class Program 
    { 
     private static DictionaryCache Cache { get; set; } 

     [Cache] 
     private static int Calc(int b) 
     { 
      Thread.Sleep(5000); 
      return b + 5; 
     } 

     private static void Main(string[] args) 
     { 
      Cache = new DictionaryCache(); 

      Console.WriteLine("Begin calc 1..."); 
      var v = Calc(5); 

      // Will return the cached value 
      Console.WriteLine("Begin calc 2..."); 
      v = Calc(5); 

      Console.WriteLine("end calc 2..."); 
     } 
    } 

    public class DictionaryCache 
    { 
     public DictionaryCache() 
     { 
      Storage = new Dictionary<string, object>(); 
     } 

     private Dictionary<string, object> Storage { get; set; } 

     // Note: The methods Contains, Retrieve, Store must exactly look like the following: 

     public bool Contains(string key) 
     { 
      return Storage.ContainsKey(key); 
     } 

     public T Retrieve<T>(string key) 
     { 
      return (T)Storage[key]; 
     } 

     public void Store(string key, object data) 
     { 
      Storage[key] = data; 
     } 
    } 
} 

然而一个更复杂的解决方案将使用一个服务类,与ICACHE接口getter和构造器注入缓存。 ICache可以封装任何现有的缓存解决方案。