Lazy<'T> Constructor ()

 

Initializes a new instance of the Lazy<'T> class. When lazy initialization occurs, the default constructor of the target type is used.

Namespace:   System
Assembly:  mscorlib (in mscorlib.dll)

new : unit -> Lazy

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.

A Lazy<'T> instance that is created with this constructor does not cache exceptions. For more information, see the Lazy<'T>class or the System.Threading.LazyThreadSafetyMode enumeration.

The following example demonstrates the use of this constructor. It also illustrates the use of the Lazy<'T>(Boolean) constructor (specifying true for isThreadSafe) and the Lazy<'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 two key lines of code in this example are the creation of the initializer and the actual initialization. At the beginning of the Main method, the example creates the thread-safe lazy initializer for LargeObject:

No code example is currently available or this language may not be supported.

The example creates and starts three threads that block on a ManualResetEvent object, so that the example can release the threads all at once. The ThreadProc method that's used by all three threads calls the Value property to get the LargeObject instance:

No code example is currently available or this language may not be supported.

The Lazy<'T> class provides locking, so that only one thread is allowed to create the LargeObject instance. The example demonstrates that the other threads all get the same instance.

System_CAPS_noteNote

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.

No code example is currently available or this language may not be supported.

Universal Windows Platform
Available since 8
.NET Framework
Available since 4.0
Portable Class Library
Supported in: portable .NET platforms
Silverlight
Available since 4.0
Windows Phone Silverlight
Available since 8.0
Windows Phone
Available since 8.1
Return to top
Show: