CA2232: Mark Windows Forms entry points with STAThread

Applies to: yesVisual Studio noVisual Studio for Mac

Note

This article applies to Visual Studio 2017. If you're looking for the latest Visual Studio documentation, see Visual Studio documentation. We recommend upgrading to the latest version of Visual Studio. Download it here

Item Value
RuleId CA2232
Category Microsoft.Usage
Breaking change Non-breaking

Cause

An assembly references the System.Windows.Forms namespace, and its entry point is not marked with the System.STAThreadAttribute attribute.

Rule description

STAThreadAttribute indicates that the COM threading model for the application is single-threaded apartment. This attribute must be present on the entry point of any application that uses Windows Forms; if it is omitted, the Windows components might not work correctly. If the attribute is not present, the application uses the multithreaded apartment model, which is not supported for Windows Forms.

Note

Visual Basic projects that use the Application Framework do not have to mark the Main method with STAThread. The Visual Basic compiler does it automatically.

How to fix violations

To fix a violation of this rule, add the STAThreadAttribute attribute to the entry point. If the System.MTAThreadAttribute attribute is present, remove it.

When to suppress warnings

It is safe to suppress a warning from this rule if you are developing for the .NET Compact Framework, for which the STAThreadAttribute attribute is unnecessary and not supported.

Example

The following examples demonstrate the correct usage of STAThreadAttribute:

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);
        }
    }
}
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