I'm running into issues that I'm sure are related to multi-threading in COM. My questions are:
Every browser would have its own IWebBrowser2 object pointed to by CComPtr<IWebBrowser2>. If I have a static callback method in my BHO class, which thread would that callback arrive on? Would it be any one of the BHO threads that were created by IE?
I tried to cache all the IWebBrowser2 pointers created in every BHO and access them later from the static method. However, I think there are some issues of (un)marshalling involved. Would this work? Any suggestions on a good/different approach to doing this?
The answer to 1 depends on the threading model that you specify for your BHO. If you specify ThreadingModel as Apartment, COM will marshal all calls to your object (within each iexplore.exe process) to the same thread. If you specify ThreadingModel as Free or Both, your object may be accessed on any thread.
The answer to 2 is yes, it would work. It is generally safe to call COM methods from any thread you like, because each object advertises its threading model when it is registered and COM itself is then responsible for handling any marshalling that must occur as a result.
You might find the following links to articles about COM threading models interesting:
- Understanding and Using COM Threading Models (MSDN)
- Understanding COM Apartments, Part I (CodeGuru)
- Understanding COM Apartments, Part II (CodeGuru)
Use the GlobalInterfaceTable to access objects across threads.