什么是单线程单元(STA)什么是多线程单元(MTA)

最近在解决问题的时候不得不使用线程,从而接触到了STA和MTA,度娘给的解释大多语焉不详。在WikiPedia上面看到了比较清楚的描述,趁着能访问的间隙麻利的摘抄下来分享和自我提升。

Apartment type Description
Single-Threaded Apartment[17] (STA), (ThreadingModel=Apartment) A single thread is dedicated to execute the methods of the object. In such an arrangement, method calls from threads outside of the apartment are marshalled and automatically queued by the system (via a standard Windows message queue). Thus, the COM run-time provides automatic synchronization to ensure that each method call of an object is always executed to completion before another is invoked. The developer therefore does not need to worry about thread locking or race conditions.
Multi-Threaded Apartment[18] (MTA), (ThreadingModel=Free) The COM run-time provides no synchronization, and multiple threads are allowed to call COM objects simultaneously. COM objects therefore need to perform their own synchronization to prevent simultaneous access from multiple threads from causing a race condition. Calls to an MTA object from a thread in an STA are also marshalled.
Dynamically determined apartment (ThreadingModel=Both) In the Both apartment mode, the server auto-selects STA or MTA at object creation to match the apartment type of the calling thread.[19] This can be useful to avoid marshaling overhead when MTA servers are accessed by a STA thread.
Thread Neutral Apartment(NA), (ThreadingModel=Neutral) A special apartment without any assigned threads. When a STA or MTA thread calls a NA object in the same process, then the calling thread temporarily leaves its apartment and executes code directly in the NA without any thread switching.[20] Therefore, one can think of NA as an optimization for efficient interapartment method calls.

对照的中文翻译:

单元类型 描述
单线程单元17, (ThreadingModel=单元) 一个线程专用于执行对象的方法。在这样的安排中,来自公寓外部线程的方法调用由系统编组并自动排队(通过标准的Windows消息队列)。因此,COM运行时提供自动同步,以确保对象的每个方法调用总是在调用另一个方法之前执行到完成。因此,开发人员不需要担心线程锁定或竞争条件。
多线程单元18, (ThreadingModel=Free) COM运行时不提供同步,允许多个线程同时调用COM对象。因此,COM对象需要执行它们自己的同步,以防止来自多个线程的同步访问导致竞争条件。从STA中的线程对MTA对象的调用也被编组。
动态确定的单元(ThreadingModel=Both) 在两种公寓模式中,服务器在创建对象时自动选择STA或MTA,以匹配调用线程的公寓类型。当STA线程访问MTA服务器时,这有助于避免封送开销。
线程中性单元(NA), (ThreadingModel=中性) 没有任何分配线程的特殊单元。当STA或MTA线程在同一进程中调用NA对象时,调用线程将暂时离开其单元并直接在NA中执行代码,而不需要任何线程切换。因此,可以将NA看作是高效的公寓间方法调用的优化。

大意就是单线程单元访问外部是串行的,在前一个任务完全结束之前不会进行下一个任务(an object is always executed to completion before another is invoked),开发者一般情况下可以不用担心竞争和死锁等问题(The developer therefore does not need to worry about thread locking or race conditions.)。

文章转载自:https://www.cnblogs.com/jiangxiaoqiang/p/4278639.html

你可能感兴趣的:(线程单元,科普)