Why does WPF require a STAThread attribute to be applied to the Main method?

谁都会走 提交于 2019-12-17 15:57:13

问题


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?


回答1:


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().




回答2:


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.



来源:https://stackoverflow.com/questions/1293402/why-does-wpf-require-a-stathread-attribute-to-be-applied-to-the-main-method

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!