Let\'s take Wes Dyer\'s approach to function memoization as the starting point:
public static Func Memoize(this Func f)
{
If you already have that Lazy
type, I assume you're using .net 4.0, so you could also use the ConcurrentDictionary:
public static Func Memoize(this Func f)
{
var map = new ConcurrentDictionary>();
return a =>
{
Lazy lazy = new Lazy(() => f(a), LazyExecutionMode.EnsureSingleThreadSafeExecution);
if(!map.TryAdd(a, lazy))
{
return map[a].Value;
}
return lazy.Value;
};
}