开发者

When to use [MTAThread]? [duplicate]

This question already has answers here: Closed 12 years ago.

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 ?


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.


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜