Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

When to use [MTAThread]? [duplicate]

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 ?

like image 605
Javed Akram Avatar asked Nov 16 '10 09:11

Javed Akram


2 Answers

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.

like image 153
Hans Passant Avatar answered Nov 03 '22 23:11

Hans Passant


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.

like image 33
Darin Dimitrov Avatar answered Nov 04 '22 01:11

Darin Dimitrov