Disadvantages of Lazy?

后端 未结 7 1847
青春惊慌失措
青春惊慌失措 2021-01-31 14:37

I recently started using Lazy throughout my application, and I was wondering if there are any obvious negative aspects that I need to take into account when using Lazy<

7条回答
  •  予麋鹿
    予麋鹿 (楼主)
    2021-01-31 14:49

    I've come to use Lazy mainly because of it's concurrency capabilities while loading resources from database. Thus I got rid of lock objects and arguable locking patterns. In my case ConcurrentDictionary + Lazy as a value made my day, thanks to @Reed Copsey and his blog post

    This looks like the following. Instead of calling:

    MyValue value = dictionary.GetOrAdd(
                                 key, 
                                 () => new MyValue(key));
    

    We would instead use a ConcurrentDictionary>, and write:

    MyValue value = dictionary.GetOrAdd(
                                 key, 
                                 () => new Lazy(
                                     () => new MyValue(key)))
                              .Value;
    

    No downsides of Lazy noticed so far.

提交回复
热议问题