最近在解决问题的时候不得不使用线程,从而接触到了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. |
大意就是单线程单元访问外部是串行的,在前一个任务完全结束之前不会进行下一个任务(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.)。中文注解在这里。