1

I am dealing with a single-threaded library (not thread safe) that I want to wrap in a COM out-of-process object to get around its thread non-safety. I need a behavior where each new COM object is instantiated in its own process - some form of out-of-process singleton.

It's been a while since I've been dealing with hardcore COM so I am not sure how to approach this or whether this is at all possible without some trickery.

wpfwannabe
  • 14,587
  • 16
  • 78
  • 129

1 Answers1

5

Call CoRegisterClassObject() with the REGCLS argument set to REGCLS_SINGLEUSE. Beware of the cost, a process is not a cheap operating system object.

There is otherwise no reason why you couldn't ensure that marshaled method calls are thread-safe, just call CoInitializeEx() to ask for an STA. Works as well in a out-of-process server as it does in a in-process server. If you are only doing this to solve a threading problem then definitely favor in-process STA. Message loop required.

Hans Passant
  • 922,412
  • 146
  • 1,693
  • 2,536
  • Thanks! I know processes are expensive but that's the only way to go with this thread unsafe library. I understand the STA requirements but can you please expand on how multiple CoCreateInstance() will returned marshaled poiners to objects in multiple processes? Will each call spawn a new process? – wpfwannabe Aug 05 '12 at 17:35
  • Yes, REGCLS_SINGLEUSE forces a new process to be created. Avoid assuming there's anything special about a thread-unsafe library, practically all non-trivial libraries are thread-unsafe. That's why STA exists in the first place. The S and T mean Single Threaded. – Hans Passant Aug 05 '12 at 17:39