共用方式為


STAThreadAttribute 類別

定義

指出應用程式的 COM 線程模型是單個線程 Apartment (STA)。

public ref class STAThreadAttribute sealed : Attribute
[System.AttributeUsage(System.AttributeTargets.Method)]
public sealed class STAThreadAttribute : Attribute
[System.AttributeUsage(System.AttributeTargets.Method)]
[System.Runtime.InteropServices.ComVisible(true)]
public sealed class STAThreadAttribute : Attribute
[<System.AttributeUsage(System.AttributeTargets.Method)>]
type STAThreadAttribute = class
    inherit Attribute
[<System.AttributeUsage(System.AttributeTargets.Method)>]
[<System.Runtime.InteropServices.ComVisible(true)>]
type STAThreadAttribute = class
    inherit Attribute
Public NotInheritable Class STAThreadAttribute
Inherits Attribute
繼承
STAThreadAttribute
屬性

備註

將此屬性套用到入口點方法(C# 和 Visual Basic 中的 Main() 方法)。 它對其他方法沒有影響。 要設定你在程式碼中開始的執行緒的 apartment 狀態,請在啟動執行緒前使用 Thread.SetApartmentState or Thread.TrySetApartmentState 方法。

COM 執行緒模型僅適用於使用 COM 互通的應用程式。 COM 執行緒模型可設定為單執行緒公寓或多執行緒公寓。 只有當執行緒實際呼叫 COM 元件時,應用程式執行緒才會初始化為 COM 互通。 若未使用 COM 互操作,則執行緒未被初始化, STAThreadAttribute 且該屬性(若存在)也無效。

從 .NET Framework 2.0 版本開始,COM 互通的預設執行緒模型取決於你開發應用程式所使用的語言,如下表所示。

語言 COM 公寓模型
C# 多執行緒公寓
C++ 多執行緒公寓
Visual Basic 單線程公寓

要更改這些預設值,你可以使用 屬性 STAThreadAttribute 來設定應用程式的執行緒模型,或在啟動執行緒前呼叫 Thread.SetApartmentState or Thread.TrySetApartmentState 方法來設定特定執行緒的執行緒模型。 在 C++ 中,你也可以使用 /CLRTHREADATTRIBUTE 連結器選項來指定公寓模型。

ASP.NET 應用程式應將 @ Page 指令的 ASPCompat 屬性設為 true,以強制頁面由 STA 執行緒池服務。

以下是一些你想用屬性 STAThreadAttribute 來明確設定執行緒模型為單執行緒公寓的情況:

  • 你正在開發一個 Windows Forms 應用程式。 若 Windows Forms 應用程式與 Windows 系統元件(如剪貼簿或 Windows 通用對話框)通訊,或使用拖放等系統功能,則必須採用單執行緒。 C# 的 Windows Forms Application 範本會自動為 C# 專案新增 STAThreadAttribute 屬性。 由於單執行緒公寓模型是 Visual Basic 的預設,因此不需要這個屬性。

  • 你正在開發一個 C# 應用程式,呼叫一個 Visual Basic 函式庫,而這個函式庫又依賴 COM 互通性。 因為單執行緒公寓模式是Visual Basic的預設,你應該透過 STAThreadAttribute 屬性將應用程式的執行緒模型改為單執行緒。

  • 你的應用程式會呼叫使用單執行緒公寓模型的 COM 元件。

建構函式

名稱 Description
STAThreadAttribute()

初始化 STAThreadAttribute 類別的新執行個體。

屬性

名稱 Description
TypeId

在衍生類別中實作時,取得這個 Attribute的唯一標識碼。

(繼承來源 Attribute)

方法

名稱 Description
Equals(Object)

傳回值,這個值表示這個實例是否等於指定的物件。

(繼承來源 Attribute)
GetHashCode()

傳回這個實例的哈希碼。

(繼承來源 Attribute)
GetType()

取得目前實例的 Type

(繼承來源 Object)
IsDefaultAttribute()

在衍生類別中覆寫時,指出這個實例的值是否為衍生類別的預設值。

(繼承來源 Attribute)
Match(Object)

在衍生類別中覆寫時,傳回值,指出這個實例是否等於指定的物件。

(繼承來源 Attribute)
MemberwiseClone()

建立目前 Object的淺層複本。

(繼承來源 Object)
ToString()

傳回表示目前 物件的字串。

(繼承來源 Object)

明確介面實作

名稱 Description
_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)

適用於

另請參閱