Out-of-queue event processing from a COM server in a managed STA application

Apparently, managed event handlers received from an unmanaged COM server outside the process are called back to a random pool thread, and not to the main STA thread (as I expected). I discovered this while answering a question about Internet Explorer automation . In the DocumentComplete code below, a non-UI thread is started (therefore, the "Event thread" does not match the "Main thread" in the debug output). So I have to use this.Invoke to display the message box. As far as I know, this behavior is different from unmanaged COM clients, where events signed from the STA stream are automatically sorted back into the same stream.

What is the reason for this departure from the traditional behavior of COM? So far I have not found any links supporting this.

 using System; using System.Diagnostics; using System.Threading; using System.Windows.Forms; namespace WinformsIE { public partial class Form1 : Form { public Form1() { InitializeComponent(); } private void Form1_Load(object sender, EventArgs ev) { var ie = (SHDocVw.InternetExplorer)Activator.CreateInstance(Type.GetTypeFromProgID("InternetExplorer.Application")); ie.Visible = true; Debug.Print("Main thread: {0}", Thread.CurrentThread.ManagedThreadId); ie.DocumentComplete += (object browser, ref object URL) => { string url = URL.ToString(); Debug.Print("Event thread: {0}", Thread.CurrentThread.ManagedThreadId); this.Invoke(new Action(() => { Debug.Print("Action thread: {0}", Thread.CurrentThread.ManagedThreadId); var message = String.Format("Page loaded: {0}", url); MessageBox.Show(message); })); }; ie.Navigate("http://www.example.com"); } } } 
+4
source share
1 answer

I found the following excerpt from Adam Nathan ".NET and COM: A Complete Compatibility Guide" :

If the COM object is in the STA, any calls from the MTA threads therefore the COM object remains in its world an affinity thread. But in the other direction there is no such thread or context switch.

So this is the expected behavior. So far, this is the only (semi-official) source on this issue that I could find.

+2
source

Source: https://habr.com/ru/post/1499077/


All Articles