Sunday, March 13, 2011

Single-Threaded Apartment (STA)


Single-Threaded Apartment (STA)
In .Net, the main method used to be preceded by the following attribute declarations:
[STAThread]
static void Main() {
What is its significance?
After going through multiple blogs and sites I have concluded that if you are not using COM and none of the APIs you are going to use in your application makes use of COM in any way then don’t pay any attention to the concept of APARTMENT.
A thread must use the STA model if it intends to display any GUI. This is the reason why main method has [STAThread] attribute before it.
What is an Apartment?
A process is a collection of virtual memory space, code, data, and system resources.
A thread is code that is to be serially executed within a process.  [A processor executes threads, not processes, so each application has at least one process, and a process always has at least one thread of execution, known as the primary thread. A process can have multiple threads in addition to the primary thread]
In general, the simplest way to view the COM threading architecture is to think of all the COM objects in the process as divided into groups called apartments. A COM object lives in exactly one apartment, in the sense that its methods can legally be directly called only by a thread that belongs to that apartment. Any other thread that wants to call the object must go through a proxy.

What is Single and Multi Thread Apartment?
Single-threaded apartments consist of exactly one thread, so all COM objects that live in a single-threaded apartment can receive method calls only from the one thread that belongs to that apartment. All method calls to a COM object in a single-threaded apartment are synchronized with the windows message queue for the single-threaded apartment's thread. A process with a single thread of execution is simply a special case of this model.
Multithreaded apartments consist of one or more threads, so all COM objects that live in an multithreaded apartment can receive method calls directly from any of the threads that belong to the multithreaded apartment. Threads in a multithreaded apartment use a model called free-threading. Calls to COM objects in a multithreaded apartment are synchronized by the objects themselves.



1 comment:

Free Web Scraping Software said...

Hi,

Single threading is so much easier to code and design for than multi threading.The best you can do is to convert the entire system back to a single thread by disabling multi-threading in the system bios, rebooting. Thanks a lot.