简体   繁体   English

如何使COM对象的方法不在主线程中运行

[英]How to make COM object's method be run not in main thread

I have a windows service which implements a COM local server. 我有一个实现COM本地服务器的Windows服务。

When running as application the COM object methods are called in a separate (not in the main) thread which is just fine. 当作为应用程序运行时,COM对象方法在一个单独的(不在主)线程中调用,这很好。 Things change when running as service - then COM object methods are called in the context of the service thread which is not cool for me. 当作为服务运行时,事情会发生变化 - 然后在服务线程的上下文中调用COM对象方法,这对我来说并不酷。

I see that it has to do with apartments, MTA, STA and so on.. but I can't figure out how to force COM to call my object methods in separate thread and not in the service one. 我看到它与公寓,MTA,STA等有关..但我无法弄清楚如何强制COM在单独的线程中而不是在服务中调用我的对象方法。

May be this has something to do with registration of the com object at the service startup? 可能这与在服务启动时注册com对象有关吗?

My environment is windows 7 + delphi but c++ solutions are welcomed. 我的环境是windows 7 + delphi,但欢迎使用c ++解决方案。

Update 2011-04-26 : 更新2011-04-26
Kudos to @sharptooth and @Chris Dickson that made me search solution in direction of "message loops". 感谢@sharptooth和@Chris Dickson让我在“消息循环”的方向上搜索解决方案。

Since it's STA the app relies on a message pump to deliver the COM messages to the thread that registered the coclass. 由于它是STA,因此app依赖于消息泵来将COM消息传递给注册coclass的线程。 I relocated the registering of the coclasses into separate thread that have message loop and all com calls are now performed in that thread. 我将coclasses的注册重新定位到具有消息循环的单独线程中,并且现在在该线程中执行所有com调用。 I had tried that approach before but forgot about the message loop so this was the missing piece of the puzzle. 之前我曾尝试过这种方法,但忘记了消息循环,所以这是拼图的缺失部分。 Thanks guys! 多谢你们!

The objects will be invoked on whichever thread you registered them from. 将在您注册的任何线程上调用这些对象。 If you would like the objects to be invoked in a separate apartment (STA) you must register the class objects from that apartment. 如果您希望在单独的公寓(STA)中调用对象,则必须从该公寓注册类对象。 This can be accomplished by creating a separate thread and registering from there. 这可以通过创建一个单独的线程并从那里注册来完成。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM