4

I am developing an UI application that creates a COM object along the way. The problem is, I want to "move" this COM object entirely on a different thread.

What I do is this:

  • create the new thread I want to move the object into (with CreateThread API)
  • after entering this thread, I'm calling PeekMessage to setup a message queue for it
  • calling CoInitialize, CoCreateInstance to create the COM object, QueryInterface to get the interface I want
  • finally I call a method on the interface that displays a MessageBox with the value returned by GetCurrentThreadId() (I have access to the VB6 code of the COM library within which the object resides).

The problem is, as this message box shows, the object methods are still executed on the original UI thread, not on the thread I created and done all those steps into. One more thing to mention, after calling the interface method, I'm also setting up a classic message loop in it.

How can I change this behaviour and achieve what I want? (that is, I want the COM object calls that originate from my newly created thread to be executed ON IT, not on the original application thread)

Here's some pseudocode to make it even more clearer:

void myMainUIMethod(){
  MessageBox(GetCurrentThreadId()); // displays 1
  CreateThread(&myCOMObjectThreadProc);
}
void myCOMObjectThreadProc(){
  MessageBox(GetCurrentThreadId()); // displays 2
  CoInitialize(NULL);
  myObject = CoCreateInstance(myObjectsCLSID);
  myObjectInterface = myObject->QueryInterface(myObjectInterfaceCLSID);
  myObjectInterface->showThreadIDMessageBox(); // this would be the COM object method call
}

And, in the VB6 code of the object, here's the pseudo-definition of showThreadIDMessageBox.
Public Sub showThreadIDMessageBox()
  Call MessageBox(GetCurrentThreadId()) //displays 1, I want it to display 2
End Sub

I have achieved what I wanted by CoUninitalizing on the main thread, before creating the new thread. But why does this happen? If COM was initialized ON THE MAIN THREAD before I'm creating the new thread, maybe for some reason it had to be..I would't want the application to crash later because I had to call CoUninitialize before creating my new thread. Here's some pseudocode that illustrates that whichever thread calls CoInitialize first will be the one picked by the STA objects.

void myMainUIMethod(){
  MessageBox(GetCurrentThreadId()); // displays 1
  CoUninitialize(); // uninitialize COM on the main thread
  CreateThread(&myCOMObjectThreadProc);
  ***i: MessageBox("When you want to initialize COM on main thread, confirm this");
  CoInitialize();
}
void myCOMObjectThreadProc(){
  MessageBox(GetCurrentThreadId()); // displays 2
  ***ii: MessageBox("When you want to initialize COM on the new thread, confirm this");
  CoInitialize(NULL);
  myObject = CoCreateInstance(myObjectsCLSID);
  myObjectInterface = myObject->QueryInterface(myObjectInterfaceCLSID);
  myObjectInterface->showThreadIDMessageBox(); // this shows 2 IF ***ii is confirmed before ***i, 1 otherwise
}

Thank you very much in advance, Corneliu

5 Answers 5

6

Looks like your problem is that your COM component threading model is not specified in registry key InprocServer32. This means that object is considered as STA (single-threaded apartment) but will be loaded to main (or host) STA, not the STA that created it. This is the first thread that called CoInitialize. To be created in same STA that called CoCreateInstance you must create HKEY_LOCAL_MACHINE\SOFTWARE\Classes\CLSID\{Your CLSID}\InprocServer32@ThreadingModel registry value and set it to Apartment.

Quote from MSDN (InprocServer32 registry key documentation):

If ThreadingModel is not present or is not set to a value, the server is loaded into the first apartment that was initialized in the process. This apartment is sometimes referred to as the main single-threaded apartment (STA). If the first STA in a process is initialized by COM, rather than by an explicit call to CoInitialize or CoInitializeEx, it is called the host STA. For example, COM creates a host STA if an in-process server to be loaded requires an STA but there is currently no STA in the process.

1
  • Thank you! You are perfectly correct. Now the COM object is executed on my created thread even though I haven't CoUninitialized on the main thread. I will mark both this post and Brendan's last post as answers, since the article he pointed me at pointed this out as well (very good article by the way Brendan). Thank you all for your answers! Sep 19, 2012 at 10:49
1

I have finally achieved what I wanted! Adding a CoUninitialize call in the main UI thread, before creating the new thread has solved it. This happens because STA COM objects will be handled on the thread that first calls CoInitialize. Now all the calls to the objects methods are reported to be executed on the thread I created and the main window of the object (the COM component has a Form) is reported to belong to it too! (used WinSpy++ to test that).

There is still a question (and a problem) though..why does it behave this way? Everywhere I search on the internet I see answers telling that a STA COM component will be fully executed on the thread it is created on (provided that CoInitialize or CoInitializeEx with COINIT_APARTMENTTHREADED had been called before), no matter what. Why does it matter if I called CoInitialize on another thread before..that's just plain stupid in my opinion for Microsoft to do so :), plus it might damage the future behaviour of my application, as I stated before.

EDIT: The correct answer is the one posted by Frost. Thank you again.

1
  • This is not correct, servers explicitly marked as STA will be created in same STA thread that called CoCreateInstance. The problem is with servers that aren't marked to use any specific threading model... see my answer below :-)
    – Rost
    Sep 19, 2012 at 10:35
0

The threads are running in parallel and that's what they are meant to do. you need to synchronize between the two threads if you want one object to wait for some operation on other thread to complete. Event object will serve for your purpose.

1
  • Sorry, I think you misunderstood my question. I've done some edits to clarify it. Thank you. Sep 19, 2012 at 1:28
0

You need to choose Free Threading as the Threading Model of the COM class when creating it. With C++ ATL, this is an option in the wizard when you select New -> COM class (or something like it). In .NET languages, I think this is specified as an attribute in the class.

BTW, you don't need to call QueryInterface after CoCreateInstance (unless you need more than one interface pointer). Just pass the GUID of the interface you want as the 4th parameter to CoCreateInstance.

5
  • thanks for the tip about queryinterface. The problem is, I cannot change the threading model of the VB6 component since it is already used in other applications and it might damage it's behaviour. My question is why can't I make it run on the thread that creates it and calls CoInitialize, even with its thread model being STA? Thanks. Sep 19, 2012 at 7:50
  • ...interesting...here's something else. I thought that maybe CoInitialize is called on the main thread before I create my new thread and that it might have something to do with the thread the component chooses, so before I create the new thread, on the main thread I called CoUninitialize. Now the calls to the COM object are executed on the thread I want, the one I created the object into. Why is this happening? Sep 19, 2012 at 7:59
  • the context I'm developing in is Firebreath, which is a framework for cross-browser cross-platform plugin development. Some code is generated, that's why CoInitialize might be called before I actually create the new thread. Sep 19, 2012 at 8:00
  • I have made some extra tests and it seems that it does matter what thread calls CoInitialize first..on the main thread, I'm calling CoUninitialize just before creating the new thread. After creating the new thread, I'm calling CoInitialize to initialize COM again on the main thread. To give the new thread some time though, before I do this I display a message box which I confirm when I want. Also in the new thread I put a MessageBox just before IT'S CoInitialize too. The first message box that goes out of the two determines the thread the COM object will execute it's code into. check the edits Sep 19, 2012 at 8:31
  • I have no idea what's going on :) ... But I have another idea, do what BrendanMcK said and make all your threads' threading model multi-threaded by passing COINIT_MULTITHREADED as the second argument to CoInitializeEx. Although I'm not sure this will help if the object's threading model is single or apartment. I jsut find it confusing that both objects and threads have threading models. Sep 19, 2012 at 9:58
0

Ah, I think I might know the problem now: it sounds like the VB6 COM object you are creating was registered as single-threaded, not apartment-threaded; this means that the object gets created on whichever thread is your app is the first to call CoInitialize().

This explain the behavior you are seeing: if you let your main thread CoInitialize() first, it becomes the "main thread" as far as COM is concerned, so the CoCreate ends up creating the object on it, even though it's CoCreated on a different thread. (This is only the case for single-threaded objects.)

But when you let your other thread CoInitialize() first, it is the "main thread" for COM, so the object gets created where you want it.

Can you change the threading model of your VB object to apartment instead of single? This would enable it to get created on the thread that calls CoCreate().

The problem is, I cannot change the threading model of the VB6 component since it is already used in other applications and it might damage it's behaviour.

...looks like that won't work for you. I guess you can check what the current threading model is, and if you can confirm that it's single, then you'll have an explanation for why it behaves the way it does, which might help you work with it.

--

So why does COM behave that way? - A: legacy compat issues. The Single Thread model is a holdover from before windows had threads in the first place, when every process had just one thread, and code didn't have to make any assumptions about synchronizations between objects within a process. To preserve this illusion and allow objects that were written assuming single-threaded COM to be used in a multithreaded environment, COM introduced the 'single' model, also known as 'legacy STA'. More details on this page, scroll down or search for "Legacy STA" for the details. COM basically puts all of these 'single' objects on the same [STA] thread - and uses whichever thread just happens to be the first to call CoInitialize. When you CoUninit and CoInit again on another thread, you're essentially restarting COM; so it's now the second thread that is the new "first thread to call CoInit", so that's why COM then ends up using that one...

(Legacy STA is such an old issue is was actually hard to track down any details; nearly all other articles mention apartment, free and both options; but there's rarely details about 'single'.)

5
  • lol man you deleted your first answer and wrote another long one just to repeat what I discovered. I'm sorry, I can't mark it as an answer, it wouldn't be fair :) Sep 19, 2012 at 10:03
  • Ya, the first answer didn't make sense because I didn't understand your problem - no point having an answer floating around that doesn't match the question :) At least now you know why you are seeing what you're seeing; that's how COM's "single threaded" model works, and is actually supposed to behave this way. Doesn't help you fix it much though. (If you can't change the existing object, can you clone the project and create a new copy or a new build that is apartment threaded instead?)
    – BrendanMcK
    Sep 19, 2012 at 10:10
  • This doesn't make a lot of sense. Actually STA and Apartment is the same thing.
    – Rost
    Sep 19, 2012 at 10:31
  • @Rost; a lot of COM doesn't seem to make much sense :-P STA and Apartment aren't quite the same; STA refers to the type of apartment - it's more a property of a thread - whereas Apartment specifies a component's threading requirements. Apartment specifies that an object can live in any STA, but Single is stricter, and COM ensures that all Single objects are in the same STA.
    – BrendanMcK
    Sep 19, 2012 at 10:37
  • @BrendanMcK But there is no such usage of term 'STA' in documentation, so your text is confusing. MS refers to that you are calling 'STA' as 'unspecified threading model'. STA is used as synonym for Apartment threading model. See MSDN
    – Rost
    Sep 19, 2012 at 10:45

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.