让我们以Wes Dyer的函数memoization方法为出发点:
public static Func<A, R> Memoize<A, R>(this Func<A, R> f)
{
var map = new Dictionary<A, R>();
return a =>
{
R value;
if (map.TryGetValue(a, out value))
return value;
value = f(a);
map.Add(a, value);
return value;
};
}
Run Code Online (Sandbox Code Playgroud)
问题是,当从多个线程使用它时,我们可能会遇到麻烦:
Func<int, int> f = ...
var f1 = f.Memoize();
...
in thread 1:
var y1 = f1(1);
in thread 2:
var y2 = f1(1);
// We may be recalculating f(1) here!
Run Code Online (Sandbox Code Playgroud)
我们试着避免这种情况.锁定map:
public static Func<A, R> …Run Code Online (Sandbox Code Playgroud)