正如我已經在你的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