Dangers of C# MTA thread creating STA COM object

后端 未结 1 1209
难免孤独
难免孤独 2021-02-09 17:40

I\'m currently looking at a problem we are having in a .Net Framework 2.0 windows service (C#) that has X number of MTA threads running that access COM components. Each thread

1条回答
  •  名媛妹妹
    2021-02-09 18:13

    There are four basic "dangers" when making calls from the MTA:

    • the COM object is apartment threaded, very common, and the call must thus be marshaled to the apartment that owns the object. The technically correct wording for "STA COM". That is expensive, marshaled calls to small methods are usually 10,000x times slower.

    • the COM object doesn't support a proxy to marshal the call. That's very easy to find out, the call will fail with E_NOINTERFACE.

    • the client programmer doesn't realize that he's making a call from the MTA and forgets to marshal the interface pointer. COM cannot prevent this on calls made to an in-process COM server. You can't make this mistake in a .NET program, the CLR will always marshal, but easy to do in other runtime environments. This otherwise invokes the common wrath of making thread-unsafe calls, works when you debug the code, fails randomly in production and is impossible to debug.

    • the COM author has published his component to be compatible with MTA by declaring its ThreadingModel as Both or Free. But did not actually test his code thoroughly enough, writing thread-safe code is notoriously difficult. Especially dangerous in [ComVisible] .NET classes because they are automatically registered as Both and it is very easy to completely forget to test the code against that promise.

    Your snippet is way too inscrutable to make the call but a possible candidate for the 4th bullet. It doesn't otherwise look like any COM is involved at all. Data providers like Oracle's are normally free threaded and tested thoroughly by hundreds of thousands of programmers.

    0 讨论(0)
提交回复
热议问题