21

Possible Duplicate:
Could you explain STA and MTA?

In C# windows forms application. I have seen [STAThread] in Program.cs above Main function.

so I want to know when to use STA or MTA thread ?
How, it affects the application ?

0

2 Answers 2

21

A thread that creates any windows should always create a single-threaded apartment. An STA provides threading guarantees for any COM object that isn't thread-safe. Very few are. The COM infrastructure ensures that the methods of such an object are always called from the right thread, marshaling the call if necessary. Quite similar to Control.Begin/Invoke() but done automatically without any coding.

A number of Windows facilities rely on that guarantee. Notably the Clipboard, Drag + Drop and the shell dialogs (like OpenFileDialog) won't work properly without it. And lots of ActiveX controls, WebBrowser being a common one you'll use in a Winforms project. Making your UI thread an MTA thread causes hard to diagnose failure, deadlock being a common one. Or a quick exception when the .NET wrapper for the component double-checks that it was created on an STA.

0
9

You can't use MTA in WinForms as most of the windows controls won't work as they are not compatible with MTA. So always use MTA unless the code of your application makes calls to STA COM objects. For example in ASP.NET, MTA is the default model.

Not the answer you're looking for? Browse other questions tagged or ask your own question.