2

I'm trying to build a Winforms application with two COM components. However, one of the components only works when using [MTAThread] and the other only works with [STAThread].

What would the recommended solution be?

stakx - no longer contributing
  • 83,039
  • 20
  • 168
  • 268
hb.
  • 1,705
  • 5
  • 22
  • 43

1 Answers1

4

Windows forms requires [STAThread] to be present on it's main entry point. It will only work in Single threaded apartment state. You can use your STA COM object on the UI thread in Windows Forms, with no issues.

The typical approach for this is to create your own thread, and set the Thread.ApartmentState to MTA (although this is the default) for the separate thread. Initialize and use your MTA-Threaded COM components from within this thread.

ThreadStart threadEntryPoint = ...;

var thread = new Thread(threadEntryPoint);
thread.ApartmentState = ApartmentState.MTA;  // set this before you call Start()!
thread.Start();
stakx - no longer contributing
  • 83,039
  • 20
  • 168
  • 268
Reed Copsey
  • 554,122
  • 78
  • 1,158
  • 1,373
  • A la new Thread(() => { COMObject = new COMObject(); ...etc }).Start() ? – hb. Oct 05 '09 at 19:20
  • Yep. Normally, I don't use lambda's for a new thread, just because the thread method tends to be longer, but that would work fine.... New threads default to MTA, so you can do that for the MTA thread. It just can't be on the GUI thread since Windows Forms requires STA. – Reed Copsey Oct 05 '09 at 19:26
  • I've been trying this with threads, but it still won't work. My winform seems to be working alright w/ [MTAThread] though. Any more ideas? – hb. Oct 05 '09 at 21:51
  • @hb: Reed isn't kidding. Don't put your main gui thread into MTA. Life will explode. – Greg D Oct 14 '09 at 20:26
  • *@Reed*: I hope you don't mind that I added a short code example to your answer. `ApartmentThread` should be set before the thread is started. I thought I'd add this point to your answer. – stakx - no longer contributing Feb 01 '11 at 08:54