Detecting cross-apartment COM calls?

  • Thread starter Thread starter jlamanna
  • Start date Start date
J

jlamanna

I was wondering if there was a utility that could tell you when your C#
application is making cross-apartment COM calls. I have a fairly large
application that makes extensive use of a 3rd party object system that
is exposed to .NET through COM, and I'm really trying to avoid slow
cross-apartment calls.

Also, is using Invoke() on a class created from the main thread a
solution to making COM calls into that thread?

Thanks.

-- James
 
|I was wondering if there was a utility that could tell you when your C#
| application is making cross-apartment COM calls. I have a fairly large
| application that makes extensive use of a 3rd party object system that
| is exposed to .NET through COM, and I'm really trying to avoid slow
| cross-apartment calls.
|
No, there is no such a 'utility', if you want to prevent any
cross-apartment- cross-thread calls you have to make sure your COM objects
live in a 'compatible' apartment and that you access the object from the
creators thread only.


| Also, is using Invoke() on a class created from the main thread a
| solution to making COM calls into that thread?
|

If you mean Control,Invoke, the answer is no, this method is meant to
dispatch delegates to the UI thread, this has nothing to do with
cross-thread COM calls.
The CLR will automagically marshal the Interface pointer when calling a COM
method using an object reference (a RCW) from another thread as the
creator's thread, so you don't hav to take care of this.

Willy.
 
Ok.
My problem is that I have threads that I spawn (using System.Threading)
that need to access these COM objects, so I was wondering the best way
to invoke the methods on these COM objects from the creation thread but
get the results back to the other thread (similar to what Invoke() does
for UI components).
 
| Ok.
| My problem is that I have threads that I spawn (using System.Threading)
| that need to access these COM objects, so I was wondering the best way
| to invoke the methods on these COM objects from the creation thread but
| get the results back to the other thread (similar to what Invoke() does
| for UI components).
|

The best way to prevent cross-apartment/cross-thread marshaling is by
accessing the objects from the same compatible thread that created them.
Only 'Free' and 'Both' threaded (ThreadingModel = Free/Both) object
references can freely be passed across threads without incurring
cross-thread marshaling provided they are created/accessed from MTA threads.
'Apartment' object types take no marshaling hit when accessed from the
creating (STA)thread, you always pay for marshaling when their reference is
passed to another thread (STA or MTA).

Willy.
 
Back
Top