tags:

views:

159

answers:

1

I'm trying to build a WinForm application with two COM Objects. However, one of the objects only works when using [MTAThread] and the other only works with [STAThread]. What would the recommended solution be?

+3  A: 

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.

Reed Copsey
A la new Thread(() => { COMObject = new COMObject(); ...etc }).Start() ?
hb
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
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
@hb: Reed isn't kidding. Don't put your main gui thread into MTA. Life will explode.
Greg D