Was this page helpful?
Your feedback about this content is important. Let us know what you think.
Additional feedback?
1500 characters remaining
Export (0) Print
Expand All

LazyInitializer Class

.NET Framework 4.6 and 4.5

Provides lazy initialization routines.

System.Object
  System.Threading.LazyInitializer

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

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

  NameDescription
Public methodStatic memberSupported by Portable Class LibraryEnsureInitialized<T>(T)Initializes a target reference type with the type's default constructor if it hasn't already been initialized.
Public methodStatic memberSupported by Portable Class LibraryEnsureInitialized<T>(T, Func<T>)Initializes a target reference type by using a specified function if it hasn't already been initialized.
Public methodStatic memberSupported by Portable Class LibraryEnsureInitialized<T>(T, Boolean, Object)Initializes a target reference or value type with its default constructor if it hasn't already been initialized.
Public methodStatic memberSupported by Portable Class LibraryEnsureInitialized<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.
Top

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

NoteNote

The HostProtectionAttribute attribute applied to this type or member has the following Resources property value: Synchronization | ExternalThreading. The HostProtectionAttribute does not affect desktop applications (which are typically started by double-clicking an icon, typing a command, or entering a URL in a browser). For more information, see the HostProtectionAttribute class or SQL Server Programming and Host Protection Attributes.

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

.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

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

Show:
© 2015 Microsoft