Is it possible to have two instances of the COM STA of the same component?

I had a problem found here in another section , I need to access a COM component that is an STA. I ran it on a dual core computer, the process using this component only reaches 50% of the CPU. Unfortunately, the owners stated that they cannot change the component in MTA because the component is a hybrid system compiled in Matlab with C as its core.

So, I tried to load two instances of a COM class into the same process, different threads accessed it, but I couldn't, only the last instance of COM became usable. Do you know anything that could solve this problem?

I am considering running two processes of my service on the same machine in order to achieve 100% CPU. This is not a good decision, mainly because these servers will be installed outside of our infrastructure.

+1


source to share


3 answers


On the topic of multiple STA components

It is possible to have two instances of the same STA COM component and access them from C #. The only thing that can prevent you from such a scenario is the object itself, if implemented as a single object.

However, if both instances are on the same STA thread, an active call on one of the instances blocks any other calls to that thread. Thus, if you want these two instances to run in parallel, you need them to be on separate STA threads. To be safe, I would create both instances on a background thread. This should prevent blocking your UI.

Related STA vs MTA for external component



I'm not sure why a component being in C would prevent it from being an MTA object. Being an MTA, this means that an object must internally synchronize its access content access and control code across multiple threads.

WARNING: Terrible to hack! :-) If you want to experiment a little, you can go to the registry and change the external component of the threading model from Apartment to Free, just to make sure your code will work with the MTA. Their component is likely to break, although they probably didn't write thread-safe code, relying on COM to keep them safe.

Make a note in a prominent place to revert this change later, so you don't end up with a system where their code doesn't work, and spent countless hours chasing ghosts. :-)

+2


source


Francie Pernov,

I tried working with two threads and initialized com instances in the context of each thread, but the error is the same: (Exception from HRESULT: 0x80004005 (E_FAIL))



I am saving and retrieving an instance via CallContext GetData and SetData.

0


source


Try registering a second class using the same DLL. Consider that for complete safety, you might need a separate copy of the DLL with a different name.

Just remember that the STA COM class (and possibly its DLL) is not considered thread safe for multithreading, and there is nothing you can do about it external to the COM class.

-1


source







All Articles