方法: オブジェクトの遅延初期化を実行するHow to: Perform Lazy Initialization of Objects

System.Lazy<T> クラスは、オブジェクトの遅延初期化とインスタンス化を実行する操作を簡略化します。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.

Example

次の例では、Lazy<T> で値を初期化する方法を示します。The following example shows how to initialize a value with Lazy<T>. someCondition 変数を true または false に設定する他の一部のコードでは、遅延変数は必要ないものとします。Assume that the lazy variable might not be needed, depending on some other code that sets the someCondition variable to true or 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");  
      }  
  }  

Example

次の例では、System.Threading.ThreadLocal<T> クラスを使用して、現在のスレッド上の現在のオブジェクト インスタンスでのみ表示される型を初期化する方法を示します。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];
    '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

関連項目See also