2 comments

  1. Hi Frank,

    Thx for the idea of using Lazy with ConcurrentDictionary.
    However this implementation CacheDictionary leaves an unresolved problem open: producer() needs to know the “key” to create its return value. Unfortunatelly Lazy
    does not provide a standard way to pass parameters to producer().
    Using any inline implementation for producer(), and referencing the “key” local variable of Fetch method of course not a solution, because the return cacheItem.Value; statement potentiali can run in an other thread, with other actual “key” parameter than the thread which added the cacheItem to the dictionary.

    horo

  2. Hi Hero, thanks for your commens

    What I did not describe in tis or any of my previous posts on this subject is the usage pattern for this style of cache. This might be a tipic for a next post.

    In the way I use this cache, I actually do use an inline delegate for the producer that captures the key and potentially any other required variables from the surrounding scope to create the new value. This should not be a problem, because the cachekey is also used as the index in the underlying ConcurrentDictionary, so each different key will have a different instance of Lazy.

    The new GetOrAdd operation on ConcurentDictionary does solve this problem by providing the key to the producer delegate. You could just use ConcurrentDictionary directly without the need for my CacheDictionary at all. The only thing you do net get from ConcurrentDictionary.GetOrAdd() is the guarantee thet the producer will be executed exectly once, depending on your scenario that might or might not be a problem.

    frankb

Comments are closed.