Question

Apparently, managed handlers for events, sourced from an unmanaged out-of-process COM server, are called back on a random pool thread, rather than on the main STA thread (as I'd expect). I've discovered this while answering a question on Internet Explorer automation. In the code below, DocumentComplete is fired on a non-UI thread (so "Event thread" is not the same as "Main thread" in the debug output). Thus, I have to use this.Invoke to show a message box. To the best of my knowledge, this behavior is different from unmanaged COM clients, where events subscribed to from an STA thread are automatically marshalled back to the the same thread.

What is the reason behind such departure from the traditional COM behavior? So far, I haven't found any references confirming 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");
        }
    }
}
Was it helpful?

Solution

I've found the following excerpt from Adam Nathan's ".NET and COM: The Complete Interoperability Guide":

If the COM object lives in an STA, any calls from MTA threads are marshaled appropriately so the COM object remains in its world of thread affinity. But, in the other direction, no such thread or context switch occurs.

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

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top