An MTA Console application calling an STA COM object from multiple threads

前端 未结 3 1649
有刺的猬
有刺的猬 2020-12-14 03:50

Although there are many questions about COM and STA/MTA (e.g. here), most of them talk about applications which have a UI. I, however, have the following setup:

3条回答
  •  清歌不尽
    2020-12-14 04:44

    Do I need to manually create a message-pump for the main thread,

    No. It is in the MTA therefore no message pump is needed.

    or will the CLR create it for me on a new STA thread

    If COM creates the thread (because there is no STA in the process) then it also creates the message pump (and a hidden window: can be seen with the SPY++ and similar debugging tools).

    COM object from any worker thread without the need of explicit synchronization

    Depends.

    If the reference to the single threaded object (STO) was created in the MTA then COM will supply the appropriate proxy. This proxy is good for all threads in the MTA.

    In any other case the reference will need to be marshalled to ensure it has the correct proxy.

    is better in terms of performance

    The only answer to this is to test both and compare.

    (Remember if you create the thread for the STA and then instantiate the object locally you need to do the message pumping. It is not clear to me that there is any CLR level lightweight message pump—including WinForms just for this certainly isn't.)

    NB. The only in depth explanatory coverage of COM and the CLR is .NET and COM: The Complete Interoperability Guide by Adam Nathan (Sams, January 2002). But it is based on .NET 1.1 and now out of print (but there is a Kindle edition and is available via Safari Books Online). Even this book doesn't describe directly what you are trying to do. I would suggest some prototyping.

提交回复
热议问题