| title | ms.custom | ms.date | ms.prod | ms.reviewer | ms.suite | ms.technology | ms.tgt_pltfrm | ms.topic | helpviewer_keywords | ms.assetid | caps.latest.revision | author | ms.author | manager | ||
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
How to: Perform Lazy Initialization of Objects |
03/30/2017 |
.net-framework |
|
article |
|
8cd68620-dcc3-4f20-8835-c728a6820e71 |
10 |
rpetrusha |
ronpet |
wpickett |
How to: Perform Lazy Initialization of Objects
The xref:System.Lazy%601?displayProperty=nameWithType class simplifies the work of performing lazy initialization and instantiation of objects. By initializing objects in a lazy manner, you can avoid having to create them at all if they are never needed, or you can postpone their initialization until they are first accessed. For more information, see Lazy Initialization.
Example
The following example shows how to initialize a value with xref:System.Lazy%601. Assume that the lazy variable might not be needed, depending on some other code that sets the someCondition variable to true or false.
Dim someCondition As Boolean = False
Sub Main()
'Initializing a value with a big computation, computed in parallel
Dim _data As Lazy(Of Integer) = New Lazy(Of Integer)(Function()
Dim result =
ParallelEnumerable.Range(0, 1000).
Aggregate(Function(x, y)
Return x + y
End Function)
Return result
End Function)
' do work that may or may not set someCondition to True
' ...
' Initialize the data only if needed
If someCondition = True Then
If (_data.Value > 100) Then
Console.WriteLine("Good data")
End If
End If
End Sub static bool someCondition = false;
//Initializing a value with a big computation, computed in parallel
Lazy<int> _data = new Lazy<int>(delegate
{
return ParallelEnumerable.Range(0, 1000).
Select(i => Compute(i)).Aggregate((x,y) => x + y);
}, LazyExecutionMode.EnsureSingleThreadSafeExecution);
// Do some work that may or may not set someCondition to true.
// ...
// Initialize the data only if necessary
if (someCondition)
{
if (_data.Value > 100)
{
Console.WriteLine("Good data");
}
} Example
The following example shows how to use the xref:System.Threading.ThreadLocal%601?displayProperty=nameWithType class to initialize a type that is visible only to the current object instance on the current thread.
[!code-csharpCDS#13] [!code-vbCDS#13]
See Also
xref:System.Threading.LazyInitializer?displayProperty=nameWithType
Lazy Initialization