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
2009-10-05 19:13:01
A la new Thread(() => { COMObject = new COMObject(); ...etc }).Start() ?
hb
2009-10-05 19:20:11
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
2009-10-05 19:26:53
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
2009-10-05 21:51:14
@hb: Reed isn't kidding. Don't put your main gui thread into MTA. Life will explode.
Greg D
2009-10-14 20:26:49