Share via


CA2232:使用 STAThread 标记 Windows 窗体的入口点

类型名

MarkWindowsFormsEntryPointsWithStaThread

CheckId

CA2232

类别

Microsoft.Usage

是否重大更改

原因

某程序集引用了 System.Windows.Forms 命名空间,但没有使用 System.STAThreadAttribute 特性标记该程序集的入口点。

规则说明

STAThreadAttribute 指示应用程序的 COM 线程模型是单线程单元。 使用 Windows 窗体的任何应用程序的入口点上必须存在此特性;如果没有此特性,则 Windows 组件可能无法正常工作。 如果不存在此特性,则应用程序使用 Windows 窗体不支持的多线程单元模型。

提示

使用应用程序框架的 Visual Basic 项目不必使用 STAThread 标记 Main 方法。 Visual Basic 编译器会自动进行标记。

如何解决冲突

要修复与该规则的冲突,请将 STAThreadAttribute 特性添加到入口点。 如果存在 System.MTAThreadAttribute 特性,请移除该特性。

何时禁止显示警告

如果为不需要并且不支持 STAThreadAttribute 特性的 .NET Compact Framework 进行开发,则可以安全地禁止显示与该规则有关的警告。

示例

下面的示例演示 STAThreadAttribute 的正确用法。

Imports System
Imports System.Windows.Forms

NameSpace UsageLibrary

Public Class MyForm
   Inherits Form

   Public Sub New()
      Me.Text = "Hello World!"
   End Sub 'New

   ' Satisfies rule: MarkWindowsFormsEntryPointsWithStaThread.
   <STAThread()> _
   Public Shared Sub Main()
      Dim aform As New MyForm()
      Application.Run(aform)
   End Sub

End Class

End Namespace
using System; 
using  System.Windows.Forms;

namespace UsageLibrary
{
    public class MyForm: Form
    {
        public MyForm()
        {
            this.Text = "Hello World!";
        }

        // Satisfies rule: MarkWindowsFormsEntryPointsWithStaThread.
        [STAThread]
        public static void Main()
        {
            MyForm aform = new MyForm();
            Application.Run(aform);
        }
    }
}