Search code examples
c#asp.net-web-apicomstamta

Calling STA COM object from WebApi


Is C#'s Runtime Callable Wrapper around a STA remote application type library safe (from the thread model and apartments perspective) to be called from a MTA thread context (.Net WebApi request)?

Should I change the server STA application to MTA or the RCW will handle these mechanisms behind the scenes?


Solution

  • An RCW is a .NET proxy for the COM proxy. It doesn't matter which apartment you're on in your .NET application, the RCW will handle marshaling for you.

    And since the object is remote, you don't need to worry if apartments are compatible, the communication crosses processes. If you'd be using a native language and environment, such as C++, you'd only have to worry not to share the COM proxy across apartments, or in other words, to properly marshal proxy references in each apartment.

    If the object was in-process, you'd gain performance for sharing the same apartment, but between processes, marshaling and thread scheduling delays will be the greatest overhead.

    However, you should consider what apartment other application uses. Applications that use an STA will be single-threaded, so this will be a bottleneck for your ASP.NET application. If it uses an MTA, perhaps not, if it doesn't synchronize all calls or if the critical sections are fast.

    For applications, you usually can't control the used apartment. How would you change its apartment? Is this a COM+ component? Is this your code? Is it ready for the apartment switch?