通过


MTAThreadAttribute 类

定义

指示应用程序的 COM 线程模型是多线程单元(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
继承
MTAThreadAttribute
属性

注解

将此属性应用于入口点方法(C# 和 Visual Basic 中的 Main() 方法)。 它对其他方法没有影响。 若要设置在代码中启动的线程的单元状态,请在启动线程之前使用 Thread.SetApartmentStateThread.TrySetApartmentState 方法。

COM 线程模型仅适用于使用 COM 互操作的应用程序。 COM 线程模型可以设置为单线程单元或多线程单元。 如果线程实际调用 COM 组件,则仅针对 COM 互操作初始化应用程序线程。 如果未使用 COM 互操作,则不会初始化线程,并且 MTAThreadAttribute 属性(如果存在)不起作用。

COM 互操作的默认线程模型取决于要在其中开发应用程序的语言,如下表所示。

语言 COM 单元模型
C# 多线程单元
C++ 多线程单元
Visual Basic 单线程单元

若要更改这些默认值,请使用 MTAThreadAttribute 属性为应用程序设置线程模型,或者在启动线程之前调用 Thread.SetApartmentStateThread.TrySetApartmentState 方法来设置特定线程的线程模型。 在 C++ 中,还可以使用 /CLRTHREADATTRIBUTE (Set CLR Thread Attribute) 链接器选项指定单元模型。

在以下情况下,使用 MTAThreadAttribute 特性将线程模型显式设置为多线程单元:

  • 你正在开发一个调用 C# 库的Visual Basic应用,而 C# 库又依赖于 COM 互操作。 由于多线程单元模型是 C# 的默认值,因此应使用 MTAThreadAttribute 属性将应用的线程模型更改为多线程模型。
  • 应用程序调用使用多线程单元模型的 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)

将一组名称映射为对应的一组调度标识符。

(继承自 Attribute)
_Attribute.GetTypeInfo(UInt32, UInt32, IntPtr)

检索对象的类型信息,该信息可用于获取接口的类型信息。

(继承自 Attribute)
_Attribute.GetTypeInfoCount(UInt32)

检索对象提供的类型信息接口的数量(0 或 1)。

(继承自 Attribute)
_Attribute.Invoke(UInt32, Guid, UInt32, Int16, IntPtr, IntPtr, IntPtr, IntPtr)

提供对对象公开的属性和方法的访问。

(继承自 Attribute)

适用于

另请参阅