Thread-safe memoization

前端 未结 7 1008
庸人自扰
庸人自扰 2020-12-07 16:53

Let\'s take Wes Dyer\'s approach to function memoization as the starting point:

public static Func Memoize(this Func f)
{         


        
7条回答
  •  一生所求
    2020-12-07 17:29

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

提交回复
热议问题