A brief introduction to the implementation of lazy initialization in C#.
Define lazy initialization: Lazy initialization of an object means that its creation is deferred until it is first used. (For this topic, lazy initialization and lazy instantiation are synonyms.) Lazy initialization is primarily used to improve performance, avoid wasteful computation, and reduce program memory requirements.
Microsoft offers three solutions to this problem, with the focus on Lazy.
Usage is nothing to talk about. One line of code.
There are two main attributes. The first is Value, which is used to get the initialized model Value.
The other is IsValueCreated to determine whether the model is initialized.
In addition to these two attributes, there is the enumeration LazyThreadSafetyMode.
There are a lot of online introductions for it, I will not talk nonsense, straight to the subject.
Main logic implementation
Let’s look at the metadata first.
Lazy defines six constructors, and we’ll focus on the sixth.
The incoming delegate is received by m_valueFactory. So when is it called? After some searching, it was called in a method called “CreateValue”.
But here I still failed to solve the puzzle in the heart, although it is called here, but this is a private method ah, and then had to follow the lead up to find. After a long time, it finally found its “previous home” : LazyInitValue.
But isn’t that still a fucking private method? Play with people? But now we have to do it again. Finally, we found the end point: the Value attribute.The result is that, despite Microsoft’s big talk, the implementation method is not complicated. It only performs the fetch when we call the Value attribute.