如何:执行对象的延迟初始化

System.Lazy<T> 类简化了执行对象的延迟初始化和实例化的工作。 通过以延迟方式实例化对象,可避免在根本不需要的情况下必须创建所有的对象,或者可以将对象的初始化延迟到第一次访问它们的时候。 有关更多信息,请参见延迟初始化

示例

下面的示例演示如何使用 Lazy<T> 初始化值。 假定延迟变量可能不是必需的,具体取决于将 someCondition 变量设置为 true 或 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");
      }
}

下面的示例演示如何使用 System.Threading.ThreadLocal<T> 类来初始化仅对当前线程上的当前对象实例可见的类型。

    'Initializing a value per thread, per instance
    Dim _scratchArrays =
        New ThreadLocal(Of Integer()())(Function() InitializeArrays())

    ' use the thread-local data
    Dim tempArr As Integer() = _scratchArrays.Value(i)
    ' ...
End Sub

Function InitializeArrays() As Integer()()
    Dim result(10)() As Integer
    ' Initialize the arrays on the current thread.
    ' ... 

    Return result
End Function
//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];

请参见

参考

System.Threading.LazyInitializer

概念

延迟初始化