[原文]http://msdn.microsoft.com/en-us/library/ms809971.aspx
Objects and Apartments
If you've so much as cracked a book on COM, you've undoubtedly come across the term apartment, which describes the constructs in which COM objects are created. If you're unfamiliar with this concept, the often-used analogy of an apartment building may help to clarify.
If you think of the building as an application's process, each apartment is a distinct area in which a COM object can be created. As with the more tangible kind of apartment, a COM apartment is a fairly self-contained unit that shares some similarities with other apartments in the same building/process. But just as there may be lofts, studios, and 2- or 3-bedroom apartments in the same building, there can also be different types of COM apartments within a process. Apartments may also be vacant or have any number of people/objects living in them.
It may be helpful to remember a few key points about COM apartments:
- An apartment is not a thread. The one-to-one relationship between threads and single-threaded apartments may lead you to believe that the two terms are interchangeable—they are not.
- An object is not an apartment. Objects are created in apartments.
- A particular instance of an object can belong to only one apartment.
- An apartment's concurrency model, whether it is single-threaded or multi-threaded, cannot be changed after it is created.
- A process can have zero or more single-threaded apartments—one for each thread that calls CoInitialize .
- A process has one multi-threaded apartment or none at all—all threads that call CoInitializeEx with COINIT_MULTITHREADED share the same apartment.
对象以及套间
如果你在COM的书上抓狂,那么毫无疑问你碰到了套间这个术语.这个术语主要用来描述创建COM对象的环境.套间经常被拿来与公寓做比喻,这种比喻对理解套间十分有帮助.
如果把应用程序所在的进程比喻成为一栋建筑,那么每一个公寓就是一个独立的区域.这就是构建COM对象的环境.像每一个现实中的公寓一样,一个COM的套间是一个完全独立的单位,并且与进程/建筑中的其他公寓有一些共同点.但是就像大楼中的公寓,有的有阁楼,有的有2个或者3个卧室,一个进程中也可以有不同种类的COM套间.套间或许是空的,也有可能有许多人/对象居住其中.
记住下面的一些关键点将会对理解套间有一些帮助:
<1>一个套间不是一个线程.线程与单线程套间是一对一的关系.这种关系会导致你认为线程和套间是一马事,其实不是;
<2>一个对象不是一个套间.对象在套间中创建.
<3>对象的实例只能属于一个套间.
<4>一个套间当前的模型,不管是单线程套间还是多线程套间,都不能在创建之后改变;
<5>一个进程可以有0个或者多个单线程套间-每个套间对应一个调用Coinitialize的线程;
<6>一个进程可以有一个或没有多线程套间.每一个调用参数为COINIT_MULTITHREADED的ConInitializeEx的线程共享相同的套间.