Rule Definition
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.
Remediation
Add the STAThreadAttribute attribute to the entry point i.e. static void main method.
Violation Code Sample
using System;
using System.Windows.Forms;
namespace UsageLibrary
{
public class MyForm: Form
{
public MyForm()
{
this.Text = "Hello World!";
}
//VIolation
public static void Main()
{
MyForm aform = new MyForm();
Application.Run(aform);
}
}
}
Fixed Code Sample
using System;
using System.Windows.Forms;
namespace UsageLibrary
{
public class MyForm: Form
{
public MyForm()
{
this.Text = "Hello World!";
}
[STAThread] //Violation Fixed
public static void Main()
{
MyForm aform = new MyForm();
Application.Run(aform);
}
}
}
Reference
https://docs.microsoft.com/en-us/visualstudio/code-quality/ca2232?view=vs-2019
Related Technologies
Technical Criterion
Programming Practices - Unexpected Behavior
About CAST Appmarq
CAST Appmarq is by far the biggest repository of data about real IT systems. It's built on thousands of analyzed applications, made of 35 different technologies, by over 300 business organizations across major verticals. It provides IT Leaders with factual key analytics to let them know if their applications are on track.