views:

12

answers:

1

I dont know if is possible.

I want a class to encapsulate all Cache of my site. I thinking about the best way to do this to avoid conflict with keys.

My first idea is something like this:

    public static TResult Cachear<TResult>(this Cache cache, Expression<Func<TResult>> funcao)
    {
        string chave = funcao.ToString();

        if (!(cache[chave] is TResult))
        {
            cache[chave] = funcao.Compile()();
        }

        return (TResult)cache[chave];
    }

Is the best way? Ty

+1  A: 

Expression.ToString() is rather expensive.

The other problem is that Expression's are always freshly created objects, so they will never have the same reference, so using that as a key is problematic.

One last issue (that does not affect you (yet)), is considering all possible parameter combination's.

The only thing I can suggest is to forget about Expression's, and just use Func<R> directly.

leppie
Expression advantage about Func its exactly about parameters. ToString return entire expression.I dont understand the problem with key. Its a string.PS: Ops, expression return parameters names, dont values =/
Fujiy
@Fujiy: The ToString method is expensive compared to a very fast lookup, and possibly even the compilation of the Expression.
leppie
The principal problem is how to get a unique string based on parameters and method name
Fujiy
@Fujiy: There are several ways to deal with that. Eg create an encapsulating object to calculate the XOR'd hash of all the parameters (as well as equality). Not sure how to handle the method name though (I have done it before, but do not have the code anymore). Search for Memomization for tips (I think there is something in the Reactive extensions).
leppie