THREADING AND COM
The Component Object Model (COM) was Microsoft’s previous technology for building components. Many organizations have legacy COM objects that they need to use in their applications. A goal of COM was to ensure that different technologies could use one another’s components, and so a COM object written in VB 6 could be used from COM code written in C++—or at least that was the theory. The problem was that VB was not multithread aware and so internally made assumptions about which thread it was running on. C++ code could quite happily be multithreaded, and so by calling a VB component directly from a C++ one could potentially cause spectacular crashes. Therefore, thread-aware and thread-unaware code needed to be kept separate, and this was achieved by the notion of apartments.
Thread-unaware components lived in Single Threaded Apartments (STAs), which would ensure they were always called on the same thread. Other components could elect to live in the Multithreaded Apartment (MTA ) or an STA (in fact there was a third option for these COM objects, but for brevity we’ll omit that). In the MTA a COM object
could be called by any MTA thread at any time so they had to be written with thread safety in mind.
Threads that did COM work had to declare whether they wanted to run their own STA or to join the MTA . The critical thing is that the overhead of calling from an MTA thread to an STA component, and vice versa, involved two thread switches and so was far less efficient that intra-apartment invocation.
Generally, then, you should always attempt to call a COM component from the same apartment that it lives in.
Thread-unaware components lived in Single Threaded Apartments (STAs), which would ensure they were always called on the same thread. Other components could elect to live in the Multithreaded Apartment (MTA ) or an STA (in fact there was a third option for these COM objects, but for brevity we’ll omit that). In the MTA a COM object
could be called by any MTA thread at any time so they had to be written with thread safety in mind.
Threads that did COM work had to declare whether they wanted to run their own STA or to join the MTA . The critical thing is that the overhead of calling from an MTA thread to an STA component, and vice versa, involved two thread switches and so was far less efficient that intra-apartment invocation.
Generally, then, you should always attempt to call a COM component from the same apartment that it lives in.
댓글
댓글 쓰기