【问题标题】:Fody - method cachingFody - 方法缓存
【发布时间】:2013-08-18 22:11:09
【问题描述】:

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

【问题讨论】:

  • 为什么第二个函数调用与第一个函数调用不一样?你只是在休眠线程,没有缓存在那里的操作。
  • 好的,我应该使用什么来完成以下操作:第一次调用:缓存参数作为键,返回值作为值。任何其他调用:如果 cache[arg1, arg2,...] 存在返回缓存值而不完成函数?
  • 据我了解,如果一个函数被缓存,它不应该被执行,但它的值应该从缓存中返回。我不明白为什么 Thread.Sleep(..) 不合适?

标签: c# method-chaining fody


【解决方案1】:

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-01-31
    • 2015-11-12
    • 2017-01-15
    • 2011-07-16
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多