Single-Threaded Apartments vs Multi-Threaded Apartments [duplicate]

瘦欲@ 提交于 2019-11-27 18:43:56

STA (single-threaded apartment) and MTA (multi-threaded apartment) are to do with COM. COM components can be designed to be accessed by a single thread, in which case it they are hosted in an STA, or they can be made internally thread safe, and hosted in an MTA. A process can have only one MTA, but many STAs. If you're only going to consume COM components all that you really need to know is that you have to match the apartment to the component or nasty things will happen.

In actuality, STAs and MTAs have an impact on .NET code. See Chris Brumme's blog entry for way more detail then you probably need:

https://devblogs.microsoft.com/cbrumme/apartments-and-pumping-in-the-clr/

It's really important to understand how STAs pump messages in .NET. It does have consequences.

Lou Franco

If your COM object needs to believe that it is in a single-threaded environment, use STA. You are guaranteed that the creation and all calls will be made by the same thread. You can safely use Thread local storage and you don't need to use critical sections.

If your COM object can be accessed by many threads simultaneously, use MTA -- there will be no guards put in place.

As others have pointed out, it generally has little impact on .NET applications.

However, be aware that the Microsoft test host used for unit tests is actually implemented in an STA, which means that there are limitations on what you can do in unit test. For example you cannot do a WaitAll on a WaitHandle in a unit test is you're using Microsoft's test host.

You don't have to worry about it unless you're doing COM-interop, in which case there are marshalling issues. It has no ramifications for .net itself.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!