Winforms: one COM object needs a STAThread, another needs an MTAThread. How can I use them?

I am trying to create a Winforms application with two COM components. However, one of the components only works when used [MTAThread]

and the other only works with [STAThread]

.

What is the recommended solution?

+2


source to share


1 answer


Windows forms require [STAThread] at the main entry point. It will only work in a single threaded apartment state. You can use your STA COM object on a UI thread in Windows Forms without issue.

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



ThreadStart threadEntryPoint = ...;

var thread = new Thread(threadEntryPoint);
thread.ApartmentState = ApartmentState.MTA;  // set this before you call Start()!
thread.Start();

      

+4


source







All Articles