What does [STAThread] do?

odiseh picture odiseh · Sep 1, 2009 · Viewed 218.9k times · Source

I am learning C# 3.5 and I want to know what [STAThread] does in our programs?

Answer

Noldorin picture Noldorin · Sep 1, 2009

The STAThreadAttribute is essentially a requirement for the Windows message pump to communicate with COM components. Although core Windows Forms does not use COM, many components of the OS such as system dialogs do use this technology.

MSDN explains the reason in slightly more detail:

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.

This blog post (Why is STAThread required?) also explains the requirement quite well. If you want a more in-depth view as to how the threading model works at the CLR level, see this MSDN Magazine article from June 2004 (Archived, Apr. 2009).