LazyInitializer Class
TOC
Collapse the table of content
Expand the table of content

LazyInitializer Class

.NET Framework (current version)
 

Provides lazy initialization routines.

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

System.Object
  System.Threading.LazyInitializer

[HostProtectionAttribute(SecurityAction.LinkDemand, Synchronization = true, 
	ExternalThreading = true)]
public static class LazyInitializer

NameDescription
System_CAPS_pubmethodSystem_CAPS_staticEnsureInitialized<T>(T)

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

System_CAPS_pubmethodSystem_CAPS_staticEnsureInitialized<T>(T, Boolean, Object)

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

System_CAPS_pubmethodSystem_CAPS_staticEnsureInitialized<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.

System_CAPS_pubmethodSystem_CAPS_staticEnsureInitialized<T>(T, Func<T>)

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

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

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);

Universal Windows Platform
Available since 4.5
.NET Framework
Available since 4.0
Portable Class Library
Supported in: portable .NET platforms
Windows Phone Silverlight
Available since 8.0
Windows Phone
Available since 8.1

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

Return to top
Show:
© 2016 Microsoft