共用方式為


延遲初始化

物件的「延遲初始化」表示其建立過程會延遲到首次使用時才進行。 (在本主題中,「延遲初始設定」和「延遲具現化」二詞為同義字。)延遲初始設定主要是用來改善效能,避免不必要的計算,並減少程式記憶體需求。 以下為最常見的案例:

  • 當建立某個物件會耗費大量資源,而程式可能不使用它時。 例如,假設您在記憶體中有 Customer 物件,它的 Orders 屬性包含大型的 Order 物件陣列,其初始化需要連接資料庫。 如果使用者從未要求顯示訂單,或使用資料進行計算,就沒必要使用系統記憶體或計算週期來建立它。 使用 Lazy<Orders> 宣告延遲初始設定 Orders 物件,可在不使用物件時,避免浪費系統資源。

  • 當建立某個物件會耗費大量資源,而您想要延遲到完成其他耗費資源的作業後,再建立它。 例如,假設當程式啟動時會載入數個物件執行個體,但只有部分是立即需要的。 您可以延遲到必要的物件皆已建立後,再對不需要的物件進行初始設定,以改善程式的啟動效能。

雖然您可以自行撰寫程式碼執行延遲初始設定,但仍建議您改用 Lazy<T>Lazy<T> 及其相關類型也支援安全執行緒,並提供一致的例外狀況傳播原則。

下表列出 .NET Framework 第 4 版提供的類型,以在不同案例中啟用延遲初始化。

類型 描述
Lazy<T> 為任何類別庫或使用者定義類型提供延遲初始化語意的包裝函式類別。
ThreadLocal<T> 類似於 Lazy<T>,不同之處在於它在執行緒本地上提供延遲初始化的語意。 每個執行緒都可以存取自己的唯一值。
LazyInitializer 為物件的延遲初始化提供進階的方法 static (在 Visual Basic 中為 Shared),而不需要類別的額外負擔。

基本延遲初始化

若要定義延遲初始化類型,例如 MyType,請使用 Lazy<MyType> (Visual Basic 為 Lazy(Of MyType)),如下列範例所示。 如果沒有委派傳入 Lazy<T> 建構函式,第一次存取 Value 屬性時,會使用 Activator.CreateInstance 建立包裝類型。 如果類型沒有無參數建構函式,則會擲回執行階段例外狀況。

在下例中,假設 Orders 是類別,包含從資料庫擷取的 Order 物件陣列。 Customer 物件包含 Orders 的執行個體,但視使用者的動作而 定,可能不需要來自 Orders 物件的資料。

// Initialize by using default Lazy<T> constructor. The
// Orders array itself is not created yet.
Lazy<Orders> _orders = new();
' Initialize by using default Lazy<T> constructor. The 
'Orders array itself is not created yet.
Dim _orders As Lazy(Of Orders) = New Lazy(Of Orders)()

您也可以在 Lazy<T> 建構函式中傳遞委派,此建構函式會在特定時間於包裝類型上叫用特定的建構函式多載,執行任何其他需要的初始設定步驟,如下列範例中所示。

// Initialize by invoking a specific constructor on Order when Value
// property is accessed
Lazy<Orders> _orders = new(() => new Orders(100));
' Initialize by invoking a specific constructor on Order 
' when Value property is accessed
Dim _orders As Lazy(Of Orders) = New Lazy(Of Orders)(Function() New Orders(100))

建立 Lazy 物件後,只有在第一次存取 Lazy 變數的 Orders 屬性時,才會建立 Value 的實例。 第一次存取時,會建立並傳回包裝類型,儲存以供未來存取。

// We need to create the array only if displayOrders is true
if (s_displayOrders == true)
{
    DisplayOrders(_orders.Value.OrderData);
}
else
{
    // Don't waste resources getting order data.
}
' We need to create the array only if _displayOrders is true
If _displayOrders = True Then
    DisplayOrders(_orders.Value.OrderData)
Else
    ' Don't waste resources getting order data.
End If

Lazy<T> 物件總是返回初始化時相同的物件或值。 因此,Value 屬性是唯讀的。 如果 Value 儲存參考型別,您就無法指派新的物件給它。 (不過,您可以變更其可設定的公用欄位和屬性的值。)如果 Value 儲存實值型別,您就無法修改其值。 不過,您可以使用新的引數再次叫用變數的建構函式,建立新的變數。

_orders = new Lazy<Orders>(() => new Orders(10));
_orders = New Lazy(Of Orders)(Function() New Orders(10))

新的 lazy 實例與舊版一樣,會等到第一次存取其 Orders 屬性時,才會具現化 Value

執行緒安全的初始化

預設情況下,Lazy<T> 物件是執行緒安全的。 也就是說,如果建構函式不指定執行緒安全的種類,它建立的 Lazy<T> 物件就會是安全執行緒。 在多執行緒案例中,第一個存取安全執行緒 Value 物件的 Lazy<T> 屬性的執行緒,會將它初始化以在所有的執行緒上進行所有的後續存取,且所有執行緒都共用相同的資料。 因此,哪個執行緒初始化物件不重要,只要是良性的競爭條件即可。

注意

您可以使用例外快取來擴展錯誤狀況的一致性。 如需詳細資訊,請參閱下一節延遲物件的例外狀況

以下範例顯示,相同的 Lazy<int> 執行個體在三個獨立的執行緒中具有相同的值。

// Initialize the integer to the managed thread id of the
// first thread that accesses the Value property.
Lazy<int> number = new(() => Environment.CurrentManagedThreadId);

Thread t1 = new(() => Console.WriteLine($"number on t1 = {number.Value} ThreadID = {Environment.CurrentManagedThreadId}"));
t1.Start();

Thread t2 = new(() => Console.WriteLine($"number on t2 = {number.Value} ThreadID = {Environment.CurrentManagedThreadId}"));
t2.Start();

Thread t3 = new(() => Console.WriteLine($"number on t3 = {number.Value} ThreadID = {Environment.CurrentManagedThreadId}"));
t3.Start();

// Ensure that thread IDs are not recycled if the
// first thread completes before the last one starts.
t1.Join();
t2.Join();
t3.Join();

/* Sample Output:
    number on t1 = 11 ThreadID = 11
    number on t3 = 11 ThreadID = 13
    number on t2 = 11 ThreadID = 12
    Press any key to exit.
*/
' Initialize the integer to the managed thread id of the 
' first thread that accesses the Value property.
Dim number As Lazy(Of Integer) = New Lazy(Of Integer)(Function()
                                                          Return Thread.CurrentThread.ManagedThreadId
                                                      End Function)

Dim t1 As New Thread(Sub()
                         Console.WriteLine("number on t1 = {0} threadID = {1}",
                                           number.Value, Thread.CurrentThread.ManagedThreadId)
                     End Sub)
t1.Start()

Dim t2 As New Thread(Sub()
                         Console.WriteLine("number on t2 = {0} threadID = {1}",
                                           number.Value, Thread.CurrentThread.ManagedThreadId)
                     End Sub)
t2.Start()

Dim t3 As New Thread(Sub()
                         Console.WriteLine("number on t3 = {0} threadID = {1}",
                                           number.Value, Thread.CurrentThread.ManagedThreadId)
                     End Sub)
t3.Start()

' Ensure that thread IDs are not recycled if the 
' first thread completes before the last one starts.
t1.Join()
t2.Join()
t3.Join()

' Sample Output:
'       number on t1 = 11 ThreadID = 11
'       number on t3 = 11 ThreadID = 13
'       number on t2 = 11 ThreadID = 12
'       Press any key to exit.

如果每個執行緒需要個別的資料,請使用 ThreadLocal<T> 類型,如本主題稍後所述。

某些 Lazy<T> 建構函式有名為 isThreadSafe 的布林參數,用來指定是否從多個執行緒存取 Value 屬性。 如果您只打算從一個執行緒存取屬性,請傳入 false 以取得適度的效能優勢。 如果打算從多個執行緒同時存取屬性,請傳遞 true 指示 Lazy<T> 執行個體正確處理一個執行緒在初始化階段擲出例外狀況的競態條件。

某些 Lazy<T> 建構函式有名為 LazyThreadSafetyModemode 參數。 這些建構函式提供其他的執行緒安全性模式。 下表顯示指定執行緒安全性的建構函式參數如何影響 Lazy<T> 物件的執行緒安全性。 每個建構函式最多只有一個這類參數。

物件的執行緒安全性 LazyThreadSafetyMode mode 參數 布林 isThreadSafe 參數 沒有執行緒安全性參數
完全執行緒安全;一次只有一個執行緒嘗試初始化該值。 ExecutionAndPublication true 是。
不具備安全執行緒。 None false 不適用。
完整的安全執行緒,多個執行緒競相初始化值。 PublicationOnly 不適用。 不適用。

如本表所示,指定 LazyThreadSafetyMode.ExecutionAndPublication 參數的 mode 如同指定 true 參數的 isThreadSafe,而指定 LazyThreadSafetyMode.None 如同指定 false

如需 ExecutionPublication 所指內容的詳細資訊,請參閱 LazyThreadSafetyMode

指定 LazyThreadSafetyMode.PublicationOnly 可讓多個執行緒嘗試初始化 Lazy<T> 執行個體。 只有一個執行緒可贏得這場競賽,所有其他的執行緒都會收到成功的執行緒所初始化的值。 如果在初始化期間,對執行緒擲回例外狀況,該執行緒就不會收到成功的執行緒所設定的值。 例外狀況不會被快取,所以後續嘗試存取 Value 屬性會導致成功初始化。 這不同於其他方法處理例外狀況的方式,下節中會對此加以說明。 如需詳細資訊,請參閱 LazyThreadSafetyMode 列舉。

延遲物件的例外狀況

如前所述,Lazy<T> 物件一律會傳回隨之初始化的相同物件或值,因此 Value 屬性是唯讀的。 如果啟用例外狀況快取,此不變性也會延伸至例外狀況行為。 如果延遲初始化的物件啟用了例外狀況快取,並在第一次存取 Value 屬性時,從其的初始設定方法擲回例外狀況,則後續每次嘗試存取 Value 屬性都會擲回相同的例外狀況。 換句話說,即使在多執行緒案例中,也絕對不會重新叫用包裝類型的建構函式。 因此,Lazy<T> 物件無法在某次存取中擲回例外狀況,並在後續存取中傳回值。

當您使用任何採用初始設定方法 (System.Lazy<T> 參數) 的 valueFactory 建構函式時,就啟用了例外狀況快取;例如,它會在您使用 Lazy(T)(Func(T)) 建構函式時啟用。 如果建構函式也採用 LazyThreadSafetyMode 值 (mode 參數),請指定 LazyThreadSafetyMode.ExecutionAndPublicationLazyThreadSafetyMode.None。 指定初始設定方法,可啟用這兩種模式的例外狀況快取。 初始設定方法可以非常簡單。 例如,這可能會呼叫 T 的無參數建構函式:在 C# 中使用 new Lazy<Contents>(() => new Contents(), mode),或在 Visual Basic 中使用 New Lazy(Of Contents)(Function() New Contents())。 如果您使用未指定初始設定方法的 System.Lazy<T> 建構函式,則不會快取 T 的無參數建構函式所擲回例外狀況。 如需詳細資訊,請參閱 LazyThreadSafetyMode 列舉。

注意

如果您建立的 Lazy<T> 物件是將 isThreadSafe 建構函式參數設定為 false,或將 mode 建構函式參數設定為 LazyThreadSafetyMode.None,您即必須從單一執行緒存取 Lazy<T> 物件,或提供您自己的同步處理。 這適用該物件的所有層面,包括例外狀況快取。

如前一節中所述,透過指定 Lazy<T> 所建立的 LazyThreadSafetyMode.PublicationOnly 物件,會以不同的方式處理例外狀況。 有了 PublicationOnly,多個執行緒可爭奪初始化 Lazy<T> 執行個體。 本例中未快取例外狀況,但會繼續嘗試存取 Value 屬性,直到成功初始化。

下表摘要說明 Lazy<T> 建構函式控制例外狀況快取的方式。

建構函式 執行緒安全模式 使用初始設定方法 已快取例外狀況
懶惰(T)() ExecutionAndPublication
懶惰(T)(Func(T)) ExecutionAndPublication 是的 是的
懶惰(T)(布爾值) True (ExecutionAndPublication) 或 false (None)
懶(T)(Func(T), 布爾值) True (ExecutionAndPublication) 或 false (None) 是的 是的
Lazy(T)(LazyThreadSafetyMode) 使用者指定的
Lazy(T)(Func(T), LazyThreadSafetyMode) 使用者指定的 是的 如果使用者指定了 PublicationOnly 則為否;否則為是。

實作延遲初始化的屬性

若要使用延遲初始設定來實作一個公用屬性,請將此屬性的支援欄位定義為 Lazy<T>,並在此屬性的 Value 存取子中傳回 get 屬性。

class Customer
{
    private readonly Lazy<Orders> _orders;
    public string CustomerID { get; private set; }
    public Customer(string id)
    {
        CustomerID = id;
        _orders = new Lazy<Orders>(() =>
        {
            // You can specify any additional
            // initialization steps here.
            return new Orders(CustomerID);
        });
    }

    public Orders MyOrders
    {
        get
        {
            // Orders is created on first access here.
            return _orders.Value;
        }
    }
}
Class Customer
    Private _orders As Lazy(Of Orders)
    Public Shared CustomerID As String
    Public Sub New(ByVal id As String)
        CustomerID = id
        _orders = New Lazy(Of Orders)(Function()
                                          ' You can specify additional 
                                          ' initialization steps here
                                          Return New Orders(CustomerID)
                                      End Function)

    End Sub
    Public ReadOnly Property MyOrders As Orders

        Get
            Return _orders.Value
        End Get

    End Property

End Class

Value 屬性是唯讀的;因此,公開此屬性的屬性不包含任何 set 存取子。 如果您需要 Lazy<T> 物件支援的讀取/寫入屬性,set 存取子必須建立新的 Lazy<T> 物件,並指派到備份存放區。 set 存取子必須建立 Lambda 運算式,傳回已傳遞給 set 存取子的新屬性值,並將該 Lambda 運算式傳遞至新 Lazy<T> 物件的建構函式。 下一次存取 Value 屬性會初始化新的 Lazy<T>,且其 Value 屬性之後也會傳回已指派給屬性的新值。 之所以如此迂迴排列,是為了保留內建在 Lazy<T> 的多執行緒保護。 否則,屬性存取子就必須快取 Value 屬性傳回的第一個值,且只能修改快取的值,而您則必須撰寫自己的執行緒安全程式碼以完成此作業。 因為 Lazy<T> 物件支援的讀取/寫入屬性需要額外的初始設定,效能可能不太令人滿意。 此外,根據特定的案例,可能需要其他協調以避免 setter 與 getter 之間的競爭條件。

執行緒本地延遲初始化

在某些多執行緒的情況下,您可能想要向各執行緒提供它專用的私用資料。 這類資料稱為「執行緒區域資料」。 在 .NET Framework 3.5 版或更舊的版本中,您可以將 ThreadStatic 屬性套用到靜態變數,使其成為執行緒區域變數。 不過,使用 ThreadStatic 屬性可能會導致極其細小的錯誤。 例如,即使基本的初始化陳述式,也只會在第一個存取它的執行緒上初始化變數,如下列範例所示。

[ThreadStatic]
static int s_counter = 1;
<ThreadStatic()>
Shared counter As Integer

在所有其他的執行緒上,變數都是使用其預設值 (零) 來初始化。 在 .NET Framework 版本 4 中,作為替代方案,您可以使用 System.Threading.ThreadLocal<T> 類型來建立一個基於實例的執行緒本地變數,該變數會由您提供的 Action<T> 委派初始化於所有執行緒上。 在下列範例中,存取 counter 的所有執行緒都會看到其起始值為 1。

ThreadLocal<int> _betterCounter = new(() => 1);
Dim betterCounter As ThreadLocal(Of Integer) = New ThreadLocal(Of Integer)(Function() 1)

ThreadLocal<T> 包裝其物件的方法,和 Lazy<T> 極其相似,但有以下基本差異:

  • 每個執行緒都是使用不能從其他執行緒存取的專用私用資料,來初始化執行緒區域變數。

  • ThreadLocal<T>.Value 屬性是讀寫的,不限修改次數。 這會影響例外狀況傳播,例如,一個 get 作業可能會引發例外狀況,但下一個卻可以成功初始化值。

  • 如未提供任何初始設定委派,則 ThreadLocal<T> 會使用預設的類型值初始化其包裝類型。 在這方面,ThreadLocal<T>ThreadStaticAttribute 屬性一致。

下列範例示範,存取 ThreadLocal<int> 執行個體的每一個執行緒都會取得自己唯一的資料複本。

// Initialize the integer to the managed thread id on a per-thread basis.
ThreadLocal<int> threadLocalNumber = new(() => Environment.CurrentManagedThreadId);
Thread t4 = new(() => Console.WriteLine($"threadLocalNumber on t4 = {threadLocalNumber.Value} ThreadID = {Environment.CurrentManagedThreadId}"));
t4.Start();

Thread t5 = new(() => Console.WriteLine($"threadLocalNumber on t5 = {threadLocalNumber.Value} ThreadID = {Environment.CurrentManagedThreadId}"));
t5.Start();

Thread t6 = new(() => Console.WriteLine($"threadLocalNumber on t6 = {threadLocalNumber.Value} ThreadID = {Environment.CurrentManagedThreadId}"));
t6.Start();

// Ensure that thread IDs are not recycled if the
// first thread completes before the last one starts.
t4.Join();
t5.Join();
t6.Join();

/* Sample Output:
   threadLocalNumber on t4 = 14 ThreadID = 14
   threadLocalNumber on t5 = 15 ThreadID = 15
   threadLocalNumber on t6 = 16 ThreadID = 16
*/
' Initialize the integer to the managed thread id on a per-thread basis.
Dim threadLocalNumber As New ThreadLocal(Of Integer)(Function() Thread.CurrentThread.ManagedThreadId)
Dim t4 As New Thread(Sub()
                         Console.WriteLine("number on t4 = {0} threadID = {1}",
                                           threadLocalNumber.Value, Thread.CurrentThread.ManagedThreadId)
                     End Sub)
t4.Start()

Dim t5 As New Thread(Sub()
                         Console.WriteLine("number on t5 = {0} threadID = {1}",
                                           threadLocalNumber.Value, Thread.CurrentThread.ManagedThreadId)
                     End Sub)
t5.Start()

Dim t6 As New Thread(Sub()
                         Console.WriteLine("number on t6 = {0} threadID = {1}",
                                           threadLocalNumber.Value, Thread.CurrentThread.ManagedThreadId)
                     End Sub)
t6.Start()

' Ensure that thread IDs are not recycled if the 
' first thread completes before the last one starts.
t4.Join()
t5.Join()
t6.Join()

'Sample(Output)
'      threadLocalNumber on t4 = 14 ThreadID = 14 
'      threadLocalNumber on t5 = 15 ThreadID = 15
'      threadLocalNumber on t6 = 16 ThreadID = 16 

Parallel.For 和 ForEach 的執行緒區域變數

當您使用 Parallel.For 方法或 Parallel.ForEach 方法並行遍歷資料來源時,可以使用內建支援執行緒區域資料的多載。 在這些方法中,執行緒區域性是通過使用區域委派來建立、存取和清理資料來實現的。 如需詳細資訊,請參閱如何:撰寫含有執行緒區域變數的 Parallel.For 迴圈如何:撰寫含有分割區域變數的 Parallel.ForEach 迴圈

低負荷情況下使用延遲初始設定

在必須延遲初始化大量物件的情況下,您可能會判定,包裝 Lazy<T> 中的每個物件需要太多記憶體或太多的運算資源。 或者,您可能對延遲初始設定的公開方式有嚴格的要求。 在這種情況下,您可以使用 static 類別的 Shared 方法(在 Visual Basic 中為 System.Threading.LazyInitializer),以在不把每個物件包裝於 Lazy<T> 的實例中的方式進行延遲初始化。

在以下範例中,假設您不將整個 Orders 物件包裝在一個 Lazy<T> 物件中,而是僅在必要時延遲初始化各個 Order 物件。

// Assume that _orders contains null values, and
// we only need to initialize them if displayOrderInfo is true
if (displayOrderInfo == true)
{
    for (int i = 0; i < _orders.Length; i++)
    {
        // Lazily initialize the orders without wrapping them in a Lazy<T>
        LazyInitializer.EnsureInitialized(ref _orders[i], () =>
        {
            // Returns the value that will be placed in the ref parameter.
            return GetOrderForIndex(i);
        });
    }
}
' Assume that _orders contains null values, and
' we only need to initialize them if displayOrderInfo is true
If displayOrderInfo = True Then


    For i As Integer = 0 To _orders.Length
        ' Lazily initialize the orders without wrapping them in a Lazy(Of T)
        LazyInitializer.EnsureInitialized(_orders(i), Function()
                                                          ' Returns the value that will be placed in the ref parameter.
                                                          Return GetOrderForIndex(i)
                                                      End Function)
    Next
End If

請注意,本例是在每次反覆迴圈時叫用初始化程序。 在多執行緒案例中,第一個叫用初始化程序的執行緒,其值會被所有執行緒看到。 後續其他執行緒也會叫用初始化程序,但其結果不被採用。 如果無法接受這種潛在的競爭條件,請使用採用布林值引數和同步處理物件的 LazyInitializer.EnsureInitialized 多載。

另請參閱