Skip to main content

Specifying Whether Lazy Instantiated Object Should Be Thread-Safe

//
// Thread-safe Lazy Instantiation
//
// In the example below, we indicate that the listOfAllFamousDogs object should
// only be created (by calling GenerateBigListOfFamousDogs) just before it is
// referenced.  The GenerateBigListOfFamousDogs method returns an instance of
// List<Dog>.
private static Lazy<List<Dog>> listOfAllFamousDogs = new Lazy<List<Dog>> (GenerateBigListOfFamousDogs);

//
// Non Thread-safe Lazy Instantiation
//
// In the Lazy<T> constructor, we specify a delegate that will be called to
// initialize our object.  By default, this results in a thread-safe
// implementation that lazily instantiates the specified object. If we do not
// need thread-safety, we can pass a second parameter to the Lazy<T>
// constructor, with a value of false.
private static Lazy<List<Dog>> listOfAllFamousDogs = new Lazy<List<Dog>> (GenerateBigListOfFamousDogs, false);