Reputation: 25223
Can anyone help me to understand the benefit of using System.Lazy with Singleton Design Pattern.
Upvotes: 13
Views: 10379
Reputation: 2579
The best source on C# Singletons (also covers Lazy<>
) belongs to Jon Skeet: http://csharpindepth.com/Articles/General/Singleton.aspx
Suppose you want to have a class that :
If most of the above conditions are true, you will need to ensure that the class is Singleton, and the unique instance is lazily initialized (not initialized until needed) If you target C# 4.0 or later, using Lazy<>
makes your design simpler, more readable and easier to remember.
Upvotes: 22
Reputation: 55907
The docs say
Use an instance of Lazy(Of T) to defer the creation of a large or resource-intensive object or the execution of a resource-intensive task, particularly when such creation or execution might not occur during the lifetime of the program.
So you make the singleton instance only if you need it.
Lazy instantiation is useful generally so that all the creation costs are not paid when the application insitialises - may give a nicer user experience.
Upvotes: 2