Thread-safe memoization

前端 未结 7 1005
庸人自扰
庸人自扰 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:49

    No, they are not better options.

    The version with the lazy evaluation is pointless as you evaluate it immediately anyway. The version with the synchronisation dictionary doesn't work properly as you are not protecting the map dictionary inside a lock before using it.

    The version that you called horrible is actually the best option. You have to protect the map dictionary inside a lock so that only one thread at a time can access it. The dictionary is not thread safe, so if you let one thread read from it while another thread is changing it, you will have problems.

    Remember that using lock on the map object doesn't protect the map object in itself, it's only using the map reference as an identifier to keep more than one thread at a time to run the code inside the lock. You have to put all code that accesses the object inside the lock, not just the code that is changing the object.

    0 讨论(0)
提交回复
热议问题