UI thread blocks background thread calling COM object

I am working on an application that communicates with an external device through a third-party COM library. I am trying to ensure that all communication with the device passes through the background thread, to prevent communication problems from screwing my application and to get rid of some other difficulties associated with the message in the user interface thread.

The problem is that whenever something happens that causes the main UI thread to block (i.e. MessageBox.Show gets called or even just moves the window around the screen), communication with the device in the background thread also stops.

Is there any way (except for a completely separate process) to split two streams far enough apart so that they do not interfere with each other? (Note that the same code with some mathematical calculations to slow things down works a bit, this is great, only when I use the COM library, I have a problem)

+4
source share
2 answers

The behavior that you observe can be explained if the following two conditions are true.

  • A third-party COM library is designed to work in a single-threaded apartment.
  • You create an instance of the class from the library in the user interface thread.

Since the user interface thread works in STA (single-threaded apartment), and the COM class was created in this thread, then all class calls originating from a thread other than the user interface thread will be distributed across the user interface thread itself. If the UI thread is blocked, all calls to the COM class are also blocked.

+11
source

I would like to fill out Brian's answer.

Maybe you forgot to call TrySetApartmentState(ApartmentState.STA) for your workflow? If so, I believe your workflow runs in the MTA by default, and all STA objects are created on a separate STA thread (possibly even in the main user interface thread). You need to make sure your workflow joins the STA and sees if this helps.

In addition, COM objects can be registered as main-STA. IIRC, this is unusual. Main-STA MUST objects live in the main user interface thread. If this happens, I believe that your only option is to resort to a workflow instead of a workflow.

+2
source

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


All Articles