Export (0) Print
Expand All

Lazy(Of T) Constructor

Initializes a new instance of the Lazy(Of T) class. When lazy initialization occurs, the default constructor of the target type is used.

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

'Declaration
Public Sub New

An instance that is created with this constructor may be used concurrently from multiple threads.

The thread safety mode of a Lazy(Of 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(Of T) instance.

A Lazy(Of T) instance that is created with this constructor does not cache exceptions. For more information, see theLazy(Of 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(Of T)(Boolean) constructor (specifying true for isThreadSafe) and the Lazy(Of 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:

lazyLargeObject = New Lazy(Of LargeObject)()

' The following lines show how to use other constructors to achieve exactly the 
' same result as the previous line:  
'lazyLargeObject = New Lazy(Of LargeObject)(True) 
'lazyLargeObject = New Lazy(Of LargeObject)(LazyThreadSafetyMode.ExecutionAndPublication)

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:

Dim large As LargeObject = lazyLargeObject.Value

The Lazy(Of 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.

NoteNote

For simplicity, this example uses a global instance of Lazy(Of T), and all the methods are static (Shared in Visual Basic). These are not requirements for the use of lazy initialization.

Imports System
Imports System.Threading

Class Program
    Private Shared lazyLargeObject As Lazy(Of LargeObject) = Nothing 

    Shared Sub Main()
        ' The lazy initializer is created here. LargeObject is not created until the  
        ' ThreadProc method executes.
        lazyLargeObject = New Lazy(Of LargeObject)()

        ' The following lines show how to use other constructors to achieve exactly the 
        ' same result as the previous line:  
        'lazyLargeObject = New Lazy(Of LargeObject)(True) 
        'lazyLargeObject = New Lazy(Of LargeObject)(LazyThreadSafetyMode.ExecutionAndPublication)


        Console.WriteLine( _
            vbCrLf & "LargeObject is not created until you access the Value property of the lazy" _
            & vbCrLf & "initializer. Press Enter to create LargeObject.")
        Console.ReadLine()

        ' Create and start 3 threads, passing the same blocking event to all of them. 
        Dim startingGate As New ManualResetEvent(False)
        Dim threads() As Thread = { New Thread(AddressOf ThreadProc), 
            New Thread(AddressOf ThreadProc), New Thread(AddressOf ThreadProc) }
        For Each t As Thread In threads
            t.Start(startingGate)
        Next t

        ' Give all 3 threads time to start and wait, then release them all at once.
        Thread.Sleep(100)
        startingGate.Set()

        ' Wait for all 3 threads to finish. (The order doesn't matter.) 
        For Each t As Thread In threads
            t.Join()
        Next t

        Console.WriteLine(vbCrLf & "Press Enter to end the program")
        Console.ReadLine()
    End Sub 


    Private Shared Sub ThreadProc(ByVal state As Object)
        ' Wait for the signal. 
        Dim waitForStart As ManualResetEvent = CType(state, ManualResetEvent)
        waitForStart.WaitOne()

        Dim large As LargeObject = lazyLargeObject.Value

        ' The following line introduces an artificial delay, to exaggerate the race  
        ' condition.
        Thread.Sleep(5)

        ' IMPORTANT: Lazy initialization is thread-safe, but it doesn't protect the   
        '            object after creation. You must lock the object before accessing it, 
        '            unless the type is thread safe. (LargeObject is not thread safe.) 
        SyncLock large
            large.Data(0) = Thread.CurrentThread.ManagedThreadId
            Console.WriteLine("Initialized by thread {0}; last used by thread {1}.", _
                large.InitializedBy, large.Data(0))
        End SyncLock 
    End Sub 
End Class 

Class LargeObject
    Private initBy As Integer = 0
    Public ReadOnly Property InitializedBy() As Integer 
        Get 
            Return initBy
        End Get 
    End Property 

    Public Sub New()
        initBy = Thread.CurrentThread.ManagedThreadId
        Console.WriteLine("LargeObject was created on thread id {0}.", initBy)
    End Sub 
    Public Data(100000000) As Long 
End Class 

' This example produces output similar to the following: 

'LargeObject is not created until you access the Value property of the lazy 
'initializer. Press Enter to create LargeObject. 

'LargeObject was created on thread id 3. 
'Initialized by thread 3; last used by thread 5. 
'Initialized by thread 3; last used by thread 4. 
'Initialized by thread 3; last used by thread 3. 

'Press Enter to end the program

.NET Framework

Supported in: 4.6, 4.5, 4

.NET Framework Client Profile

Supported in: 4

Portable Class Library

Supported in: Portable Class Library

Supported in: Windows Phone 8.1

Supported in: Windows Phone Silverlight 8.1

Supported in: Windows Phone Silverlight 8
Show:
© 2015 Microsoft