When to lazy load?

后端 未结 8 1834
庸人自扰
庸人自扰 2020-12-31 17:14

I lazy load all my members. I have been doing this for a while and simply taken lazy load to be a good thing at face value.

Let\'s say we have

publi         


        
8条回答
  •  迷失自我
    2020-12-31 17:29

    From the code I am seeing, you are not doing lazy load. You are initializing members in the constructor, which always happens and happens very soon in the lifetime of the instance.

    Hence, I am wondering, what is not-lazy loading for you?

    Lazy loading is usually when you only initialize something when you are accessing it.

    Here an example, using .NET 4.0 Lazy class, which helps you in doing just that, lazy loading:

    public class Foo
    {
        private Lazy _value = new Lazy(() => 3);
    
        public int Value { get { return _value.Value; } }
    }
    

    Regarding thread-safety - you can pass a second argument LazyThreadSafetyMode which knows two ways to specify thread-safety: One in which execution of the initialization method may happen several times, but where all threads get the value that was created first, or one where the execution is also protected against being run several times.

提交回复
热议问题