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.

APTTYPE Result
CURRENT Same as Co­Get­Object­Context
STA Not allowed
MTA Returns the multithreaded apartment
NA Returns the neutral apartment
MAINSTA Returns 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.

1 comment

Discussion is closed. Login to edit/delete existing comments.

  • Kalle Niemitalo 0

    The documentation of the ppv parameter of CoGetDefaultContext looks like I cannot use that function if “the object’s component has not been imported into a COM+ application”.

Feedback usabilla icon