0

我第一次使用 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,...]存在返回缓存值而不完成函数?(使用缓存属性)

4

1 回答 1

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 可以包装任何现有的缓存解决方案。

于 2013-09-24T08:19:26.683 回答