COM Interop: How can I stop it using "RPC Callback Thread"
-
Thursday, March 12, 2009 2:11 PMI'm struggling, trying to create a .NET version of the DSO Framer control (http://www.microsoft.com/downloads/details.aspx?FamilyId=CE2CA4FD-2169-4FAC-82AF-770AA9B60D77&displaylang=en) in order to host Word, Excel and so on in my application.However, it appears that .NET dramatically changes the threading system used by COM under the hood. When I run the DSO Framer control in C++, all the calls, from my code to Word and back again run in the Main thread.When I run my translation of the code in C#, calls made from Word to my application are made in an "RPC Callback Thread". If I then attempt to call Word from this code, I get an RPC_E_CANTCALLOUT_ININPUTSYNCCALL HRESULT.If I switch to MTAThread, Word deadlocks straight after a call fetching my hWnd (IOleInPlaceFrame.GetWindow),and if I use PostMessage, the code blocks.I'm tearing my hair out. I cannot see why simply running under .NET should have the Word calls back to me run ina different thread. If these calls were not running in these "RPC Callback Thread"s then I'm positive that, as in theC++ code, the calls would work 100%.So, how do I stop .NET from invoking the Word calls on the RPC Callback Thread?
Sean Hederman
All Replies
-
Friday, March 13, 2009 12:57 AMModeratorYou can't, that's how out-of-process COM works. You'll have to follow the COM threading rulez for an STA component like Word. Ensure your main thread is an STA thread ([STAThread] attribute on Main), pump a message loop (Application.Run), never block the UI thread, avoid making calls on background threads. And you'll be okay.
Hans Passant. -
Friday, March 13, 2009 4:49 AMBut hang on. Why is that not the COM threading rule for an STA VC++ app, but it IS the COM threading rule for an STA .NET app? In any case, I am in STA, I am pumping a message loop, and nothing is blocking the UI thread other than this blasted Word which is in the UI thread making non-UI thread calls.
Sean Hederman -
Thursday, March 19, 2009 4:55 AMSo, let me reiterate, it seems clear that .NET breaks the STA threading model on callbacks. The callbacks are supposed to happen on the same thread as created the COM Component, but they do not. If you write unmanaged code, the callbacks occur on the UI thread, if you write unmanaged code they happen on RPC Callback Threads. This results in blocking on the UI thread, as the main application is blocking the message pump wiating for a response which it can never receive if you wish to call the component back in one of the callbacks.There appears to be no way to have .NET actually fulfill the STA behaviour in .NET.
Sean Hederman -
Thursday, March 19, 2009 4:57 AMSorry that should read ", if you write MANAGED code they happen on RPC Callback Threads"Silly to post just after waking up :-)
Sean Hederman- Edited by Sean Hederman Thursday, March 19, 2009 5:00 AM Stuffed up again

