我第一次使用Fody方法缓存(https://github.com/Dresel/MethodCache)。我可能做错了什么,因为下面的代码不起作用:
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,...]存在返回缓存值而不完成函数?(使用缓存属性)
发布于 2013-09-24 08:19:26
正如我在您的github问题中已经指出的,静态方法缓存是在1.3.1中添加的。
在设计MethodCache.Fody时,还必须向类中添加缓存Getter,其中包含应该缓存的方法,并实现缓存。您可以编写自己的缓存程序或使用现有缓存解决方案的适配器(请参阅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可以封装任何现有的缓存解决方案。
https://stackoverflow.com/questions/18304144
复制相似问题