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
- 繼承
- 屬性
將此屬性套用至進入點方法, (Main()
C# 和 Visual Basic 中的 方法) 。 它不會影響其他方法。 若要設定您在程式代碼中啟動之線程的 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 元件。
MTAThread |
初始化 MTAThreadAttribute 類別的新執行個體。 |
Equals(Object) |
傳回值,這個值指出此執行個體是否與指定的物件相等。 (繼承來源 Attribute) |
Get |
傳回這個執行個體的雜湊碼。 (繼承來源 Attribute) |
Get |
取得目前執行個體的 Type。 (繼承來源 Object) |
Is |
在衍生類別中覆寫時,表示這個執行個體的值是衍生類別的預設值。 (繼承來源 Attribute) |
Match(Object) |
在衍生類別中覆寫時,會傳回值,表示這個執行個體是否等於指定物件。 (繼承來源 Attribute) |
Memberwise |
建立目前 Object 的淺層複製。 (繼承來源 Object) |
To |
傳回代表目前物件的字串。 (繼承來源 Object) |
_Attribute. |
將一組名稱對應至一組對應的分派識別項 (Dispatch Identifier)。 (繼承來源 Attribute) |
_Attribute. |
擷取物件的類型資訊,可以用來取得介面的類型資訊。 (繼承來源 Attribute) |
_Attribute. |
擷取物件提供的類型資訊介面數目 (0 或 1)。 (繼承來源 Attribute) |
_Attribute. |
提供物件所公開的屬性和方法的存取權。 (繼承來源 Attribute) |
產品 | 版本 |
---|---|
.NET | Core 1.0, Core 1.1, Core 2.0, Core 2.1, Core 2.2, Core 3.0, Core 3.1, 5, 6, 7, 8, 9, 10 |
.NET Framework | 1.1, 2.0, 3.0, 3.5, 4.0, 4.5, 4.5.1, 4.5.2, 4.6, 4.6.1, 4.6.2, 4.7, 4.7.1, 4.7.2, 4.8, 4.8.1 |
.NET Standard | 1.0, 1.1, 1.2, 1.3, 1.4, 1.5, 1.6, 2.0, 2.1 |
UWP | 10.0 |