[ACCEPTED]-When to use [MTAThread]?-multithreading
A thread that creates any windows should 19 always create a single-threaded apartment. An 18 STA provides threading guarantees for any 17 COM object that isn't thread-safe. Very 16 few are. The COM infrastructure ensures 15 that the methods of such an object are always 14 called from the right thread, marshaling 13 the call if necessary. Quite similar to 12 Control.Begin/Invoke() but done automatically 11 without any coding.
A number of Windows facilities 10 rely on that guarantee. Notably the Clipboard, Drag 9 + Drop and the shell dialogs (like OpenFileDialog) won't 8 work properly without it. And lots of ActiveX 7 controls, WebBrowser being a common one 6 you'll use in a Winforms project. Making 5 your UI thread an MTA thread causes hard 4 to diagnose failure, deadlock being a common 3 one. Or a quick exception when the .NET 2 wrapper for the component double-checks 1 that it was created on an STA.
You can't use MTA in WinForms as most of 5 the windows controls won't work as they 4 are not compatible with MTA. So always use 3 MTA unless the code of your application 2 makes calls to STA COM objects. For example 1 in ASP.NET, MTA is the default model.
More Related questions