次の方法で共有


方法: オブジェクトの遅延初期化を実行する

System.Lazy<T> クラスは、オブジェクトの遅延初期化とインスタンス化を実行する作業を簡略化します。 オブジェクトを遅延初期化することで、必要がない場合にはオブジェクトを作成せずに済みます。また、最初にアクセスされるまで初期化を延期することもできます。 詳細については、「 遅延初期化」を参照してください。

Example 1

次の例は、 Lazy<T>を使用して値を初期化する方法を示しています。 someCondition変数をtrueまたはfalseに設定する他のコードによっては、遅延変数が必要ない可能性があるとします。

Dim someCondition As Boolean = False

Sub Main()
    'Initialize 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 might or might 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;
  // Initialize 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);
  }, LazyThreadSafetyMode.ExecutionAndPublication);

  // Do some work that might or might not set someCondition to true...

  // Initialize the data only if necessary.
  if (someCondition)
  {
      if (_data.Value > 100)
      {
          Console.WriteLine("Good data");
      }
  }

Example 2

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

// Initialize a value per thread, per instance.
ThreadLocal<int[][]> _scratchArrays =
    new(InitializeArrays);

static int[][] InitializeArrays() => [new int[10], new int[10]];

// 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