UI线程阻塞后台线程调用COM对象

编程入门 行业动态 更新时间:2024-10-27 22:21:11
本文介绍了UI线程阻塞后台线程调用COM对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

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

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

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

解决方案

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

  • 的第三方COM库的设计是一个单线程的单元
  • 您是从UI线程
  • 由于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对象

本文发布于:2023-06-07 22:46:40,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/572858.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:线程   后台   对象   UI

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!