Could you explain STA and MTA?

前端 未结 7 2131
梦如初夏
梦如初夏 2020-11-22 04:12

Can you explain STA and MTA in your own words?

Also, what are apartment threads and do they pertain only to COM? If so, why?

7条回答
  •  花落未央
    2020-11-22 05:08

    I find the existing explanations too gobbledygook. Here's my explanation in plain English:

    STA: If a thread creates a COM object that's set to STA (when calling CoCreateXXX you can pass a flag that sets the COM object to STA mode), then only this thread can access this COM object (that's what STA means - Single Threaded Apartment), other thread trying to call methods on this COM object is under the hood silently turned into delivering messages to the thread that creates(owns) the COM object. This is very much like the fact that only the thread that created a UI control can access it directly. And this mechanism is meant to prevent complicated lock/unlock operations.

    MTA: If a thread creates a COM object that's set to MTA, then pretty much every thread can directly call methods on it.

    That's pretty much the gist of it. Although technically there're some details I didn't mention, such as in the 'STA' paragraph, the creator thread must itself be STA. But this is pretty much all you have to know to understand STA/MTA/NA.

提交回复
热议问题