Domanda

I am using Fody method cache (https://github.com/Dresel/MethodCache) for the first time. I am probably doing something wrong because the following code does not work:

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;
 }

What should I use that does the following: first call: cache arguments as keys and return value as value. any other call: if cache[arg1, arg2,...] exist return cache value without completing a function ? (using a cache attribute)

È stato utile?

Soluzione

As I already stated in your github issue, static method caching was added in 1.3.1.

As MethodCache.Fody is designed, you also have to add an Cache Getter to your class which contains the methods that should be cached and implement a Cache. You can program your own Cache or use an adapter to existing Cache solutions (see documentation of https://github.com/Dresel/MethodCache).

The minimum code for your sample (with an basic dictionary cache implementation) would look like this:

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;
        }
    }
}

However a more sophisticated solution would use a service class, with an ICache interface Getter and contructor injection of the cache. ICache could wrap any existing caching solutions.

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top