Lazy<T> Constructor (Func<T>^)
Initializes a new instance of the Lazy<T> class. When lazy initialization occurs, the specified initialization function is used.
Assembly: mscorlib (in mscorlib.dll)
An instance that is created with this constructor may be used concurrently from multiple threads.
The thread safety mode of a Lazy<T> instance that is initialized with this constructor is LazyThreadSafetyMode::ExecutionAndPublication. The thread safety mode describes the behavior when multiple threads try to initialize the Lazy<T> instance.
The following example demonstrates the use of this constructor to provide lazy initialization with exception caching. It also demonstrates the use of the Lazy<T>(Func<T>^, Boolean) constructor (specifying true for isThreadSafe) and the Lazy<T>(Func<T>^, LazyThreadSafetyMode) constructor (specifying LazyThreadSafetyMode::ExecutionAndPublication for mode). To switch to a different constructor, just change which constructors are commented out.
The example defines a LargeObject class that will be initialized lazily by one of several threads. The three key sections of code illustrate the creation of the initializer, the actual initialization, and the constructor of the LargeObject class, which demonstrates exception caching. At the beginning of the Main method, the example creates the thread-safe lazy initializer for LargeObject:
The example creates and starts three threads. The ThreadProc method that's used by all three threads calls the Value property to get the LargeObject instance:
In the constructor of the LargeObject class, the third key section of code throws an exception the first time a LargeObject instance is created, but thereafter allows instance creation to occur:
When the example is run, the first thread that tries to create an instance of LargeObject fails, and the exception is caught. You might expect that the next thread would successfully create an instance, but the Lazy<T> object has cached the exception. Because of this, all three threads throw the exception.
For simplicity, this example uses a global instance of Lazy<T>, and all the methods are static (Shared in Visual Basic). These are not requirements for the use of lazy initialization.
Available since 8
Available since 4.0
Portable Class Library
Supported in: portable .NET platforms
Available since 4.0
Windows Phone Silverlight
Available since 8.0
Available since 8.1