HOW TO:執行物件的延遲初始化
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