Difference between Stathread and Mtathread

Asked

Viewed 1,726 times

11

What is the difference between Stathread and Mtathread and when I should use one or the other?

Why and how do they only concern the COM?

1 answer

8


TL;DR: MTA and STA are behavior specifications for threads of COM objects. Use STA on objects where you cannot guarantee thread Safety.

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

The model of threading used by COM is a model of "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 started in an apartment, is part of it by the length of time of execution of the same.

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

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: https://stackoverflow.com/questions/127188/could-you-explain-sta-and-mta

Another answer goes beyond:

One thread that creates any window should always create a single-threaded Apartment. An STA gives segmentation guarantees to any object WITH which it is not thread-safe; very few are. A COM infrastructure ensures that the methods of such an object are always called from the right thread, lining up the calls if necessary. Very similar to Control.Begin / Invoke(), but done automatically, without any encoding.

A number of Windows objects have this guarantee. Notably dialog windows (such as Openfiledialog), Clipboard and Drag+Drop would not work properly without these guarantees, and also many activex controls (Webbrowser being one that you are usually used to in Winforms projects). Turn your interface into a thread MTA results in errors difficult to diagnose - deadlock being one of the most common. Or an Exception caused when the wrapper .NET to the component checks that it was created in a STA.

Hans Passant, original: https://stackoverflow.com/questions/4192646/when-to-use-mtathread

Still, according to MSDN,

An Apartment is the name given to the groups of processes where the 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 belonging to that apartment.

Original: http://msdn.microsoft.com/en-us/library/windows/desktop/ms693344(v=vs.85). aspx

Browser other questions tagged

You are not signed in. Login or sign up in order to post.