4

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");
        }
    }
}
Community
  • 1
  • 1
noseratio
  • 59,932
  • 34
  • 208
  • 486
  • How is your "Main(...)" threading, or what's the apartment state of the thread in which you call Activator.CreateInstance() – Simon Mourier Aug 27 '13 at 07:23
  • The main and the only explicit thread here is STA. The app itself is just a stock WinForms app generated by VS2012 wizard: `[STAThread] static void Main() { /* ... */ Application.Run(new Form1()); }`. – noseratio Aug 27 '13 at 07:35
  • 2
    I would think it's normal behaviour. What receives the event is a hidden COM object implemented by the CLR (a CCW or alike) that may have any threading model. Events in .NET can arrive on any thread. BTW, let's refresh memories :-) http://social.msdn.microsoft.com/Forums/vstudio/en-US/fa2798a7-8a0b-46c0-936e-eaa2a35f01b6/sta-windows-forms-application-gets-mta-events-from-com-objects – Simon Mourier Aug 27 '13 at 09:52
  • @SimonMourier, I almost remember reading somewhere they've changed the rules for COM => .NET callbacks exactly the way you described. Although the link you gave doesn't seem to state that explicitly. Nor can I find any other sources. Maybe, it was Adam Nathan's book on Interop. Let it be so, is `ie` out-of-proc proxy free-threaded? Can I safely call `ie` APIs directly from an event handler on a random thread? Also, I wonder if I can get back the traditional COM behaviour by implementing a custom `SynchronizationContext`. – noseratio Aug 27 '13 at 12:39
  • 1
    Since it's out-of-process, you can call IE on any thread I believe, COM+proxy/stubs will do the magic. I think the only way to get back to COM behavior is not rely on .NET events (delegate etc.) underlying COM implementation, but implement a manual COM event sink (IConnectionPoint, etc.). You should be able to declare this sink object apartment behavior the way you like. Never tested this seems overkill to me :-) – Simon Mourier Aug 27 '13 at 15:50

1 Answers1

2

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.

noseratio
  • 59,932
  • 34
  • 208
  • 486