UI线程阻塞后台线程调用COM对象 [英] UI thread is blocking a background thread calling a COM object

查看:118
本文介绍了UI线程阻塞后台线程调用COM对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的工作是通过第三方COM库与外部设备通信的应用程序。我试图具有对设备的所有通信通过一个后台线程既要防止问题的沟通,从拧紧了我的应用程序和摆脱通过在UI线程通信介绍了一些其他的复杂性。



现在的问题是,每当有事情发生,导致主UI线程被阻塞(被称为即MessageBox.Show甚至只是在屏幕上移动窗口),对后台设备的通信线程停止为好。



有什么办法(短一个完全独立的过程),打破了两个线程足够远,他们不会互相干扰? (注意,完全相同的代码有一些数学计算来放慢改革的步伐有点工作得很好,只有当我使用,我有问题的COM库)


解决方案

您观察到的行为可以如果以下两个条件都为真来解释。




  • 的第三方COM库的设计是一个单线程的单元

  • 您是从UI线程

  • <对图书馆创建类的实例/来运行UL>

    由于UI线程在STA(单线程单元)运行和COM类是在该线程创建然后从非UI线程的线程上的类发起的所有呼叫将被整理到UI线程本身。如果UI线程阻塞,那么所有调用COM类将阻止为好。


    I am working on an application that communicates with an external device via a third-party COM library. I'm attempting to have all communication to the device go through a background thread both to prevent problems with communication from screwing up my app and to get rid of some other complexities introduced by having communication in the UI thread.

    The problem is that whenever something happens that causes the main UI thread to block (i.e. MessageBox.Show being called or even just moving the window around the screen), the communication with the device on the background thread stops as well.

    Is there any way (short of a totally separate process) to break the two threads far enough apart that they won't interfere with each other? (Note, the exact same code with some math calculations to slow things down a bit works just fine, it's only when I'm using the COM library that I have the issue)

    解决方案

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

    • The 3rd party COM library is designed to be run in a single threaded apartment
    • You are creating an instance of a class from the library on the UI thread

    Since the UI thread runs in an STA (single threaded apartment) and the COM class was created on that thread then all calls to the class originating from a thread other than the UI thread will be marshalled onto the UI thread itself. If the UI thread is blocked then all calls to the COM class will block as well.

    这篇关于UI线程阻塞后台线程调用COM对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆