Thread safety using OCX from C # .NET

I have not used OLE / COM for some time as a developer, but currently I need to use some third-party OCX code libraries from a C # program.

The C # program uses threads (it is a TCP socket server). OCX marked as a model of streaming data. From my reading, I came to the conclusion that if I tried to create one instance of each OCX for the stream, and only to use this instance from the stream that created it, I should be fine.

I also did: -

myThread.SetApartmentState(ApartmentState.STA); 

before the start of each thread.

Should this be enough to ensure safe use of OCX?

The symptom I see is that threads can create OCX, but apparently randomly, calls to prepare and initialize OCX fail. They do not seem to return any useful information on why.

Can someone explain what I see, or give me a guide on how to safely use these OCX from multi-threaded code?

Alternatively, should I just give up and create one instance of each and all OCX in one thread and send all calls to them over a streaming network or similar?

+4
source share
3 answers

Marking a component as an apartment carving is simply a statement from the component developer. There are many component developers who donโ€™t understand streams, and even those who really understand a stream, sometimes make mistakes, so itโ€™s faith to trust this statement.

Personally, I am very afraid of using third-party components in a multi-threaded environment for this reason. Besides those that, as I know, are very widespread in multi-threaded applications and / or for which I know that I can get adequate support.

If you do not have access to the support of the developer of the component or source code for this component, and you absolutely must use it, then the possibility of creating one instance can be a good pragmatic solution.

+1
source

You do what management users probably never did before. Runtime environments such as VB6, the most common place to use .ocx, do not allow multiple STA threads to be created. It is very likely that the code inside the control contains global variables without any lock necessary to ensure security. The result is an accidental failure.

Disable it, .NET has excellent TCP support with the System.Net namespace. Socket, TcpClient, and TcpServer.

+1
source

The state of the apartment must be managed by COM, so setting the state of the apartment only affects the state of your .Net code. But the flat of your COM object should only be accessible from the thread that created your COM object (the one that calls CoInitialize). As for the failure of your calls to the COM object, they can come from the base code. What is OCX lib?

0
source

Source: https://habr.com/ru/post/1339388/


All Articles