首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >Fody -方法缓存

Fody -方法缓存
EN

Stack Overflow用户
提问于 2013-08-18 22:11:09
回答 1查看 1.4K关注 0票数 0

我第一次使用Fody方法缓存(https://github.com/Dresel/MethodCache)。我可能做错了什么,因为下面的代码不起作用:

代码语言:javascript
复制
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,...]存在返回缓存值而不完成函数?(使用缓存属性)

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2013-09-24 08:19:26

正如我在您的github问题中已经指出的,静态方法缓存是在1.3.1中添加的。

在设计MethodCache.Fody时,还必须向类中添加缓存Getter,其中包含应该缓存的方法,并实现缓存。您可以编写自己的缓存程序或使用现有缓存解决方案的适配器(请参阅https://github.com/Dresel/MethodCache文档)。

示例的最小代码(带有基本字典缓存实现)如下所示:

代码语言:javascript
复制
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可以封装任何现有的缓存解决方案。

票数 2
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/18304144

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档