Porady: wykonywanie incjalizacji obiektów z opóźnieniem

Klasa System.Lazy<T> upraszcza pracę podczas inicjowania leniwego i tworzenia wystąpień obiektów. Inicjując obiekty w leniwy sposób, możesz uniknąć konieczności ich tworzenia w ogóle, jeśli nigdy nie są potrzebne, lub można odroczyć ich inicjowanie do momentu pierwszego uzyskania dostępu. Aby uzyskać więcej informacji, zobacz Lazy Initialization (Inicjowanie z opóźnieniem).

Przykład 1

W poniższym przykładzie pokazano, jak zainicjować wartość za pomocą Lazy<T>polecenia . Załóżmy, że zmienna leniwa może nie być potrzebna, w zależności od innego kodu, który ustawia zmienną someCondition na true lub 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);  
  }, LazyThreadSafetyMode.ExecutionAndPublication);  
  
  // 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");  
      }  
  }  

Przykład 2

W poniższym przykładzie pokazano, jak za pomocą System.Threading.ThreadLocal<T> klasy zainicjować typ widoczny tylko dla bieżącego wystąpienia obiektu w bieżącym wątku.

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

Zobacz też