This documentation is archived and is not being maintained.

How to: Perform Lazy Initialization of Objects

The System.Lazy<T> 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.

The following example shows how to initialize a value with Lazy<T>. Assume that the lazy variable might not be needed, depending on some other code that sets the someCondition variable to true or false.

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

The following example shows how to use the System.Threading.ThreadLocal<T> class to initialize a type that is visible only to the current object instance on the current thread.

//Initializing a value per thread, per instance
 ThreadLocal<int[][]> _scratchArrays = 
     new ThreadLocal<int[][]>(InitializeArrays);
// . . .
 static int[][] InitializeArrays () {return new int[][]}
//   . . .
// use the thread-local data
int i = 8;
int [] tempArr = _scratchArrays.Value[i];