Difference between STAThread and MTAThread

9

What is the difference between STAThread and MTAThread and when should I use one or the other?

Why and how do they say only about COM?

    
asked by anonymous 08.07.2014 / 12:35

1 answer

7

TL; DR : MTA and STA are behavioral specifications for COM object threads. Use STA on objects where you can not guarantee thread safety .

Long version : There are two excellent answers in Stack Overflow in English. Translations, and a final addendum, follow:

  

The threading model used by COM is an "apartment"   , where the execution context of initialized COM objects is   associated with a single thread ( Single Thread Apartment ) or several   ( Multi Threaded Apartment ). In this model, a COM object, once   in an apartment, is part of it for the duration of the   execution.

     

The STA model is used for objects that are not thread-safe . That   means that they do not deal with their own synchronization - a   common is a user interface component. Therefore, if another   segment needs to interact with the object (such as pushing a button on a   form), the message is packaged into the STA segment.   Windows Forms Message Pumping is an example of this [n.t .: a processing queue] .

     

If the COM object can handle its own synchronization then the   MTA model can be used where multiple segments are allowed to   interact with the object, without controlled calls.

Joseph Daigle, original: link

Another answer goes further:

  

A thread that creates any window should always create a    single-threaded apartment . An STA provides segmentation guarantees for   any COM object that is not thread-safe ; very few are. THE   infrastructure ensures that the methods of such an object are always   calls from the correct thread, queuing calls   required. Very similar to Control.Begin / Invoke() , but done   automatically, without any encoding.

     

A number of Windows objects have this guarantee.   Notably the dialog windows (such as OpenFileDialog), Clipboard and   Drag + Drop would not work correctly without these guarantees, and also many   ActiveX controls ( WebBrowser ) being one that you are usually used to   in WinForms projects). Make your interface into an thread MTA   results in errors that are difficult to diagnose - deadlock being one of the most   common. Or an exception caused when the wrapper .NET for   component verifies that it was created in an STA.

Hans Passant, original: link

Yet, according to MSDN,

  

An Apartment is the name given to groups of processes where objects   COM are divided. A COM object exists in only one Apartment, in the   sense that their methods can only be called directly by a   thread that belongs to that apartment.

Original: link

    
08.07.2014 / 14:23