Disadvantages of Lazy?

后端 未结 7 1826
青春惊慌失措
青春惊慌失措 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 15:15

    Here's not quite a negative aspect, but a gotcha for lazy people :).

    Lazy initializers are like static initializers. They get run once. If an exception is thrown, the exception is cached and subsequent calls to .Value would throw the same exception. This is by design and is mentioned in the docs ... http://msdn.microsoft.com/en-us/library/dd642329.aspx:

    Exceptions that are thrown by valueFactory are cached.

    Hence, code as below will never return a value:

    bool firstTime = true;
    Lazy lazyInt = new Lazy(() =>
    {
        if (firstTime)
        {
            firstTime = false;
            throw new Exception("Always throws exception the very first time.");
        }
    
        return 21;
    });
    
    int? val = null;
    while (val == null)
    {
        try
        {
            val = lazyInt.Value;
        }
        catch
        {
    
        }
    }
    

提交回复
热议问题