I am developing a Windows Forms 2.0 application that references a COM primary interop assembly to communicate with a COTS product. I am still very new to working with COM from .Net and the threading issues that are involved, so I am unsure how to marshall a COM interface between threads--I have the main UI thread, of course, but for many of the data access calls I use a BackgroundWorker component to execute the calls asynchronously. The issue I am having is that I am attempting to maintain a single instance of the Database object (part of the COM API) because creating it is very resource intensive, but I am getting an exception that the worker thread is attempting to access an interface that was mashalled for a different thread. The main UI thread initially creates the Database object (this class I wrote to handle creating this Database object implements a thread-safe Singleton pattern) and the exception of course only occurs when the background worker thread attempts to call a method on the same object that the main UI thread created. I have seen multiple articles on various scenarios but none that seemed to address what I am trying to do. This is not a remoting scenario and I cannot customize the interop assemblies to change the default marshalling behavior. I can only change how my code accesses the resources in the COM API. Can someone please give me an example in C# of how to marshall a COM interface across multiple threads I was told by the technical support group that developed this COTS API to simply change the thread apartment state from STA to MTA, but I can't do this--in fact it throws an exception when the app loads to to being unable to register drag and drop..etc.
Thanks very much,
Larkin

Marshalling COM interface between threads--help!
Adnan Memon
DougMullett
Thanks for the help with these pinvokes.
Here's the mother of all pinvoke references with thanks to Adam Nathan!
www.pinvoke.net
ie: http://www.pinvoke.net/default.aspx/ole32/CoMarshalInterThreadInterfaceInStream.html
ellitech
[DllImport("ole32.dll")]
static extern int CoMarshalInterThreadInterfaceInStream([In] ref Guid riid,
[MarshalAs(UnmanagedType.IUnknown)] object pUnk, out UCOMIStream ppStm);
[DllImport("ole32.dll")]
static extern int CoGetInterfaceAndReleaseStream(UCOMIStream pStm, [In] ref
Guid riid, [MarshalAs(UnmanagedType.IUnknown)] out object ppv);
If you are going into COM itf marshaling you might want to read this as well:
http://msdn.microsoft.com/library/default.asp url=/library/en-us/com/html/0c1feee7-e33b-4b5d-8e35-4de6895e3947.asp
--Ivo
Jon Mikel Inza
dr-Wicked
Is there an API we can use to get the apartment where an object was created in
-mab
ekho
Here's an MSDN article that may help you: http://msdn2.microsoft.com/en-us/library/5s8ee185(en-US,VS.80).aspx
luoluo
xn