MTAThreadAttribute 類別
定義
重要
部分資訊涉及發行前產品,在發行之前可能會有大幅修改。 Microsoft 對此處提供的資訊,不做任何明確或隱含的瑕疵擔保。
表示應用程式的 COM 執行緒模型為多執行緒 Apartment (Multithreaded Apartment,MTA)。
public ref class MTAThreadAttribute sealed : Attribute
[System.AttributeUsage(System.AttributeTargets.Method)]
public sealed class MTAThreadAttribute : Attribute
[System.AttributeUsage(System.AttributeTargets.Method)]
[System.Runtime.InteropServices.ComVisible(true)]
public sealed class MTAThreadAttribute : Attribute
[<System.AttributeUsage(System.AttributeTargets.Method)>]
type MTAThreadAttribute = class
inherit Attribute
[<System.AttributeUsage(System.AttributeTargets.Method)>]
[<System.Runtime.InteropServices.ComVisible(true)>]
type MTAThreadAttribute = class
inherit Attribute
Public NotInheritable Class MTAThreadAttribute
Inherits Attribute
- 繼承
- 屬性
備註
將此屬性套用至 C# 和 Visual Basic) 中的 方法 (Main()
進入點方法。 它不會影響其他方法。 若要設定您在程式碼中啟動之執行緒的 Apartment 狀態,請在啟動執行緒之前使用 Thread.SetApartmentState 或 Thread.TrySetApartmentState 方法。
注意
如需 COM 執行緒模型的概觀,請參閱 瞭解和使用 COM 執行緒模型。
COM 執行緒模型僅適用于使用 COM Interop 的應用程式。 COM 執行緒模型可以設定為單一執行緒 Apartment 或多執行緒 Apartment。 只有線上程實際呼叫 COM 元件時,才會初始化 COM Interop 的應用程式執行緒。 如果未使用 COM Interop,則不會初始化執行緒,而且如果存在,則 MTAThreadAttribute 屬性不會有任何作用。
從 .NET Framework 2.0 版開始,COM Interop 的預設執行緒模型取決於您正在開發應用程式的語言,如下表所示。
Language | COM Apartment 模型 |
---|---|
C# | 多執行緒 Apartment |
C++ | 多執行緒 Apartment |
Visual Basic | 單一執行緒 Apartment |
若要變更這些預設值,您可以使用 MTAThreadAttribute 屬性來設定應用程式的執行緒模型,或在啟動執行緒之前呼叫 Thread.SetApartmentState 或 Thread.TrySetApartmentState 方法,以針對特定執行緒設定執行緒模型。 在 C++ 中,您也可以使用 /CLRTHREADATTRIBUTE (設定 CLR 執行緒屬性) 連結器選項來指定 Apartment 模型。
您想要使用 MTAThreadAttribute 屬性明確將執行緒模型設定為多執行緒 Apartment 的一些案例包括:
您正在開發可呼叫 C# 程式庫的 Visual Basic 應用程式,而該程式庫接著會依賴 COM Interop。 因為多執行緒 Apartment 模型是 C# 的預設值,所以您應該使用 MTAThreadAttribute 屬性,將應用程式的執行緒模型變更為多執行緒。
您的應用程式會呼叫使用多執行緒 Apartment 模型的 COM 元件。
建構函式
MTAThreadAttribute() |
初始化 MTAThreadAttribute 類別的新執行個體。 |
屬性
TypeId |
在衍生類別中實作時,取得這個 Attribute 的唯一識別碼。 (繼承來源 Attribute) |
方法
Equals(Object) |
傳回值,這個值指出此執行個體是否與指定的物件相等。 (繼承來源 Attribute) |
GetHashCode() |
傳回這個執行個體的雜湊碼。 (繼承來源 Attribute) |
GetType() |
取得目前執行個體的 Type。 (繼承來源 Object) |
IsDefaultAttribute() |
在衍生類別中覆寫時,表示這個執行個體的值是衍生類別的預設值。 (繼承來源 Attribute) |
Match(Object) |
在衍生類別中覆寫時,會傳回值,表示這個執行個體是否等於指定物件。 (繼承來源 Attribute) |
MemberwiseClone() |
建立目前 Object 的淺層複製。 (繼承來源 Object) |
ToString() |
傳回代表目前物件的字串。 (繼承來源 Object) |
明確介面實作
_Attribute.GetIDsOfNames(Guid, IntPtr, UInt32, UInt32, IntPtr) |
將一組名稱對應至一組對應的分派識別項 (Dispatch Identifier)。 (繼承來源 Attribute) |
_Attribute.GetTypeInfo(UInt32, UInt32, IntPtr) |
擷取物件的類型資訊,可以用來取得介面的類型資訊。 (繼承來源 Attribute) |
_Attribute.GetTypeInfoCount(UInt32) |
擷取物件提供的類型資訊介面數目 (0 或 1)。 (繼承來源 Attribute) |
_Attribute.Invoke(UInt32, Guid, UInt32, Int16, IntPtr, IntPtr, IntPtr, IntPtr) |
提供物件所公開的屬性和方法的存取權。 (繼承來源 Attribute) |
適用於
另請參閱
意見反應
https://aka.ms/ContentUserFeedback。
即將登場:在 2024 年,我們將逐步淘汰 GitHub 問題作為內容的意見反應機制,並將它取代為新的意見反應系統。 如需詳細資訊,請參閱:提交並檢視相關的意見反應