1

I have a need to pass a delegate method with a varying number and type of parameters to another method. My hope is to be able to inspect the values of the parameters within the call.

This is my generic cache class.

public T Get<T>(Expression<Func<T>> getItemCallback) where T : class
{

    T item = HttpRuntime.Cache.Get(hashRepresentationOfValues) as T;
    if (item == null)
    {
        item = getItemCallback.Compile()();
        HttpRuntime.Cache.Insert(
            hashRepresentationOfValues,
            item,
            null,
            DateTime.Now.AddMinutes(5),
            TimeSpan.Zero);
    }
    return item;
 }

My calls look like the following:

private DataContext db;
return cache.Get<List<SomeDBObject>>(
    () => db.SomeDBObjectCall(param1, param2, param3));

As you can see it would be extremely helpful if I could dynamically determine the values of the delegate call as they could be used as the cache-key.

ewahner
  • 1,149
  • 2
  • 11
  • 23

1 Answers1

1

So basically, you have a method with an unknown signature that you want to wrap for caching purposes. If that's the case, you will definitely want to look into a technique called Memoization

Memoization on Wikipedia In computing, memoization is an optimization technique used primarily to speed up computer programs by having function calls avoid repeating the calculation of results for previously processed inputs.

An example of such a function in C# would be something along these lines:

static Func<A, R> Memoize(this Func<A, R> f)
{
    var dict = new Dictionary<A, R>();
    return (A arg)=>
    {
        R result;
        if (!dict.TryGetValue(arg, out result))
        {
             result = f(arg);
             dict.Add(arg, result);
        }
        return result;
    };
}

Note that the method takes a generic Func and returns a generic Func with the same signature. This way, you can effectively wrap your methods without bogging up the rest of your code. It is really seamless!

More examples here and here

Martin Devillers
  • 17,293
  • 5
  • 46
  • 88
  • I like the generality of Memoization, but if I am not mistaken that is more or less handled by the runtime cache index. I would like to let .NET handle the management of the cache. I just need an easier method to create the cache key. – ewahner Jul 17 '12 at 16:28