Always mark Windows Forms starting point as STAThread | CAST Appmarq

Always mark Windows Forms starting point as STAThread


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

Health Factor

  Total Quality Index


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.

Benchmark Statistics

Global Compliance

nan%

Total Violations
0
Total Opportunities
0
Average Violations / App.
nan
The compliance score represents 1 minus the ratio between the number of times a rule has been violated compared to the number of opportunities in a set of applications that the rule could have been violated.

Industry Insights

Select from drop-down

100.00%

Telecommunications

99.99%

Software ISV

100.00%