I haven’t used OLE/COM for quite some time as a developer, but I currently have a need to use some 3rd party OCX code libraries from a C# program.
The C# program uses threading (it’s a TCP socket server). The OCXs are marked as Apartment threading model. From my reading, I concluded that if I was careful to create one instance of each OCX per thread, and only to use that instance from the thread that created it, I should be OK.
I did also do:-
myThread.SetApartmentState(ApartmentState.STA);
before starting each thread.
Should this be enough to ensure safe use of the OCXs?
The symptom I’m seeing is that threads can all create OCXs but on an apparently random basis, the calls to prepare and initialize the OCXs fail. They don’t seem to return any useful information as to why.
Can anyone explain what I’m seeing, or give me a guide to using these OCXs safely from threaded code?
Alternatively, should I just give up and create a single instance of each and all OCXs in one thread, and send all calls to them via a threadsafe queue or similar?
Marking a component as Apartment threaded is just an assertion from the component developer. There are plenty of component developers around who don’t understand threading, and even those who do understand threading sometimes get it wrong, so it’s an act of faith to trust this assertion.
Personally I’m very wary of using 3rd party components in a multithreaded environment for that reason. Except those that I know have had very wide exposure in multithreaded applications, and/or for which I know I can get adequate support.
If you don’t have access to support from the component developer, or source code for the component, and you absolutely need to use it, then the option of creating a single instance may be a good pragmatic solution.