正如我已经在你的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可以封装任何现有的缓存解决方案。
为什么第二个函数调用与第一个函数调用不一样?你只是在睡觉线程,没有任何操作缓存在那里。 – Tarec
好的,我应该怎样使用它:第一次调用:缓存作为键的arugments并返回值作为值。任何其他调用:如果缓存[arg1,arg2,...]存在,但没有完成函数返回缓存值? – dajuric
据我所知,如果一个函数被缓存,它不应该被执行,但它的值应该从缓存中返回。我不明白为什么Thread.Sleep(..)不合适? – dajuric