如何使用WPF接口与COM异步连接? [英] How to have an async connection to COM with a WPF interface?

查看:546
本文介绍了如何使用WPF接口与COM异步连接?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的上一个问题( SelectedIndex在tabcontrol中无法更改 - 调度程序问题

我的程序中有3个givens:

There are 3 givens in my program:


  1. 我有一个主窗口是WPF。

  2. 我连接到一个单独的应用程序(一个不同的进程),实现一个COM服务器,可以在不同的时间调用,以执行耗时的计算,其结果将显示在

  3. 我不想在等待这些计算结束时冻结主窗口。事实上,运营商应该可以继续使用该程序,但某些控制可能在异步操作结束前被禁用。

在我看来,要实现上述要求,我需要有一个单独的线程专门处理COM请求,该线程必须是STA。不知何故我调用这个线程做东西,不知何故这个线程调用GUI线程更新东西。技术上不清楚如何让这种情况发生。

It seems to me that to achieve the above requirements that I need to have a separate thread dedictated to handling COM requests and that thread must be STA. Somehow I invoke this thread to do stuff, and somehow this thread invokes the GUI thread to update stuff. It's not clear to me technically how to make this happen.

两个问题:如何在线程之间实现这些调用?

Two questions: How do I implement these calls between threads? What's a clean architecture for this?

推荐答案

根据您的COM服务器,您可以使用MTA或STA线程模型。 STA,单线程公寓是最简单的使用,我建议开始,除非你确定你的COM支持MTA,你需要使用MTA。

Depending on your COM server you may use either an MTA or an STA threading model. The STA, Single Threaded Apartment is the simplest to use and the one I would recommend to begin with unless you are certain your COM supports MTA and you need to use MTA.

调用长时间运行的COM对象的一种安全方法是以下标准模式:
- 从UI线程启动一个新的线程,从中调用COM对象。您可以使用任务或线程。将主题公寓更改为STA:System.Threading.Thread.CurrentThread.ApartmentState = ApartmentState.STA

A safe way of calling long running COM objects is the following standard pattern: - From the UI thread start a new thread where your COM object will be called from. You can use a Task or a thread. Change the Thread Apartment to STA: System.Threading.Thread.CurrentThread.ApartmentState = ApartmentState.STA


  • 可以正常实例化和运行COM对象。当它完成或当你从它需要在主UI线程上传递的事件,你提出一个事件从你的代码传递数据(不传回COM对象,你需要解耦数据从它,因为它属于另一个线程),你的UI线程将拦截。

  • Then from that thread you can instantiate and run your COM object as normal. When it has finished or when you get events from it that need to be passed on the main UI thread you raise an event from your code passing in the data (do not pass back the COM object, you need to decouple the data from it since it belongs to another thread) which your UI thread will intercept.

回到事件时,在UI线程上,如果使用WinForm,则需要使用InvokeRequired / BeginInvoke。我不知道WPF,但我希望你需要同步回调与UI线程太。

On your UI thread when you get back the event, you will need to use InvokeRequired / BeginInvoke if you use WinForm. I am not sure about WPF but I would expect you would need to synchronize the callback with the UI thread too.

这篇关于如何使用WPF接口与COM异步连接?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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