4

I have a windows service which implements a COM local server.

When running as application the COM object methods are called in a separate (not in the main) thread which is just fine. 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.

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.

May be this has something to do with registration of the com object at the service startup?

My environment is windows 7 + delphi but c++ solutions are welcomed.

Update 2011-04-26:
Kudos to @sharptooth and @Chris Dickson that made me search solution in direction of "message loops".

Since it's STA the app relies on a message pump to deliver the COM messages to the thread that registered the 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. I had tried that approach before but forgot about the message loop so this was the missing piece of the puzzle. Thanks guys!

Nedko
  • 567
  • 4
  • 12
  • 1
    Do you run a message loop to dispatch requests? – sharptooth Mar 09 '11 at 06:53
  • 2
    Please could you clarify what you mean by the distinction between "when running as application" and "when running as service" and whether the client calls are coming from a different process in both cases. Also, when you register the COM coclass, what apartment model are you specifying? – Chris Dickson Mar 14 '11 at 18:00
  • @sharptooth: the service's thread has message loop – Nedko Apr 26 '11 at 12:25
  • @Chris Dickson: I am able to run the exe as both an application and as a service as well - in the first case it is run in the current user's session i.e. the user executs it manually, in the second case it runs as System started by "net start". The model is automatically set by the Delphi VCL as STA. I register the coclasses in the main/service thread (when running respectively as app/service). The calls are coming from an outer test application (exe). – Nedko Apr 26 '11 at 12:34

1 Answers1

1

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. This can be accomplished by creating a separate thread and registering from there.