Why does WPF require a STAThread attribute to be a

2019-01-14 12:36发布

I am new to WPF, and in every tutorial I read, they either have a [System.STAThread] attribute applied to their Main method, or they tell the reader to do that.

Is this attribute really "required"? And if so, why?

标签: wpf sta
2条回答
孤傲高冷的网名
2楼-- · 2019-01-14 13:22

There's an excellent answer for this in this blog entry.

Quoting from the blog:

When the STAThreadAttribute is applied, it changes the apartment state of the current thread to be single threaded. Without getting into a huge discussion about COM and threading, this attribute ensures the communication mechanism between the current thread and other threads that may want to talk to it via COM. When you're using Windows Forms, depending on the feature you're using, it may be using COM interop in order to communicate with operating system components. Good examples of this are the Clipboard and the File Dialogs.

Windows Forms is not supported within a MTA or free threaded apartment. Applications using Windows Forms should always declare the apartment style they're using, as some other component could initialize the apartment state of thread improperly.

查看更多
太酷不给撩
3楼-- · 2019-01-14 13:29

This is more a Windows requirement than a WPF one, and goes back to the original design of Windows forms and controls, from before .NET.

STAThread refers to "Single-Threaded Apartments" which refers to the threading model used by the current (main) thread. The threading model in use dictates how other .NET and COM applications will talk to your application (and inherently, its threads). The single-threaded application model requires that no single object "live in" more than one STA thread at a time, verses the MTA thread model; and allows for the passing of pointers to data across apartments only via marshalling-as-object.

Basically, with the [STAThread] declaration, other applications will know what your thread's policy is when sending you data. The STA model is the most common threading model for Windows threads/applications; but you'll sometimes come across certain code that won't run if called from an STA-modeled thread, because it's designed to send/receive data across thread boundaries in ways that don't comply with the STA restrictions. Knowing beforehand what the apartment model of a given thread allows the IDE to catch these exceptions at compile-time instead of getting nasty access violation errors when you attempt to use an object across thread boundaries during runtime.

You can read about STA and MTA threads from the MSDN article at: http://msdn.microsoft.com/en-us/library/ms680112(VS.85).aspx

Note that even normal .NET applications (from before WPF) required the [STAThread] declaration atop of the main().

查看更多
登录 后发表回答