LazyInitializer Class

Definition

Provides lazy initialization routines.

public static class LazyInitializer
Inheritance
LazyInitializer

Examples

The following example demonstrates how to use EnsureInitialized to lazily initialize a value using a Boolean value to track whether initialization has already happened and an object to use as the mutual exclusion lock.

ExpensiveData _data = null;  
bool _dataInitialized = false;  
object _dataLock = new object();  

//  ...  

ExpensiveData dataToUse = LazyInitializer.EnsureInitialized(ref _data, ref _dataInitialized, ref _dataLock);  

Remarks

These routines avoid needing to allocate a dedicated, lazy-initialization instance, instead using references to ensure targets have been initialized as they are accessed.

Methods

EnsureInitialized<T>(T, Boolean, Object, Func<T>)

Initializes a target reference or value type by using a specified function if it hasn't already been initialized.

EnsureInitialized<T>(T, Boolean, Object)

Initializes a target reference or value type with its parameterless constructor if it hasn't already been initialized.

EnsureInitialized<T>(T, Func<T>)

Initializes a target reference type by using a specified function if it hasn't already been initialized.

EnsureInitialized<T>(T, Object, Func<T>)

Initializes a target reference type with a specified function if it has not already been initialized.

EnsureInitialized<T>(T)

Initializes a target reference type with the type's parameterless constructor if it hasn't already been initialized.

Applies to

제품 버전
.NET Core 1.0, Core 1.1, Core 2.0, Core 2.1, Core 2.2, Core 3.0, Core 3.1, 5, 6, 7, 8, 9
.NET Framework 4.0, 4.5, 4.5.1, 4.5.2, 4.6, 4.6.1, 4.6.2, 4.7, 4.7.1, 4.7.2, 4.8, 4.8.1
.NET Standard 1.0, 1.1, 1.2, 1.3, 1.4, 1.6, 2.0, 2.1
UWP 10.0

Thread Safety

The methods of LazyInitializer are thread-safe and may be called from multiple threads concurrently.

See also