Cannot use MTAThread() with WinForms

Jun 17, 2009 at 1:36 PM

Following up on last night's discussion regarding Ali's demo where we were not able to use WaitHandle.WaitAll() the short answer is that you cannot set a WinForm application to use a Multi-Threaded Apartment.   Congrats to Ali for correctly stating this fact during class despite all the conjecture surrounding this topic.

I did a little research on the topic and Microsoft does not support MTA for the WinForms API.  This is done for safety reasons in order to protect the Windows application from the generally unsafe MTA.

Another issue that you run in to with a WinForm application is that if you try and apply the MTAThread attribute to a given method what you are effectively doing is telling the application to change its orientation AFTER it has started running.  You should never change the orientation after an application is running because it can (and likely will) cause your application to become instable.  Declaring the use of STA or MTA at the outset of execution is ideal so that the correct environment can be built for the application by the O/S.  This is why the example in the book uses a console application with the MTAThread attribute decoration on the Main routine.  At the time that this method is called the environment for the console application has not been finalized so establishing the use of MTA is not an issue. 

NOTE: As Duncan mentioned last night, STA applications (like Win Forms) can call MTA applications but if there is a requirement for the STA application to handle a callback from the MTA application the Control.Invoke method must be used.  This is because the callback in .NET MTA applications do not have any thread affinity (due to its free-threaded design) and will not be received by the calling STA application.


Jun 19, 2009 at 3:25 PM

Great information gq_stud! :>  Thanks for sharing.