0

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.

stakx - no longer contributing
  • 83,039
  • 20
  • 168
  • 268
  • 2
    No, creating an appdomain 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 appdomain to take care of this, the thread creation code and the Application.Run() call needs to operate in that appdomain. – Hans Passant Jun 11 '16 at 10:31
  • @Hans, thanks for your helpful comment. Pity you didn't post it as an answer. ;-) One thing that I don't fully understand here, why `Application.Run`? Isn't that Winforms-specific (which my question was not)? I read Chris Brumme's MSDN blog on the need of STA threads to do message pumping in order to not block objects finalization (or sth. along that line) and I suppose that's why you mentioned `Application.Run` - but is it an absolute necessity? Are there alternatives? – stakx - no longer contributing Jul 02 '16 at 15:50

1 Answers1

0

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]."

Community
  • 1
  • 1
stakx - no longer contributing
  • 83,039
  • 20
  • 168
  • 268