How do I get a foothold in the neutral apartment?

Raymond Chen


The neutral apartment is a mysterious beast. You cannot initialize a thread in the neutral apartment, because the neutral apartment isn’t tied to a thread. Instead, the neutral apartment takes over any thread it can find: If you are on an existing thread and call an object that lives in the neutral apartment, the calling thread is converted to a neutral apartment thread temporarily. When the call is finished, the thread is returned to its original apartment.

That’s great, but now there’s a chicken-and-egg problem: How do you get the first object into the neutral apartment?

One way is to CoCreateInstance an object whose definition specifies that it runs in the neutral apartment. But maybe you don’t have one of those objects readily at hand. What if you just want to get into the neutral apartment directly?

The Co­Get­Default­Context function will produce an IContext­Callback for the apartment type you specify.

CURRENTSame as Get­Get­Object­Context
STANot allowed
MTAReturns the multithreaded apartment
NAReturns the neutral apartment
MAINSTAReturns the main STA

Passing APTTYPE_STA is not valid because it’s ambiguous: There can be multiple STA apartments in a process.

Asking for the APTTYPE_MAINSTA when there is no main STA will fail. And asking for anything when COM isn’t initialized will also fail.

And so we find our foothold: Calling Co­Get­Default­Context with APTTYPE_NA will return the context for the neutral apartment. You can then use the IContext­Callback::Context­Callback method to execute code in that context.


Comments are closed. Login to edit/delete your existing comments