Search code examples
c#.netappdomainapartments

How can I set the COM apartment state for code loaded with `AppDomain.ExecuteAssembly`?


When I create a Thread, I have the option of setting its COM apartment state explicitly before I start it. For example:

// using System.Threading;
var thread = new Thread(…);
thread.SetApartmentState(ApartmentState.STA);
thread.Start();

But when I create an AppDomain and load some code into it, I seem to have no explicit control over thread creation, so I have no way of calling SetApartmentState:

// using System;
var pluginAppDomain = AppDomain.Create("PluginAppDomain");
pluginAppDomain.ExecuteAssembly(@"Plugin.dll");

Is there any way to specify that the main/entry thread created inside an AppDomain should use a specific COM apartment state?

I know that Plugin.dll's main entry method could be marked with an [STAThread] or [MTAThread] attribute; but let's assume that Plugin.dll does not explicitly declare or set the COM apartment state, and that I cannot change Plugin.dll.


Solution

  • I am re-posting Hans Passant's comment above as an answer since it essentially answers most of this question:

    "No, creating an [app domain] does not create a thread. You are executing with the state of the thread that made the AppDomain.Create() call. Which is not good enough, you cannot uphold the STA promise. You'll need more code in the [app domain] to take care of this, the thread creation code and the Application.Run() call needs to operate in that [app domain]."