为什么 WPF 需要将 STAThread 属性应用于 Main 方法?
我是 WPF 新手,在我阅读的每个教程中,他们要么将 [System.STAThread]
属性应用于其 Main
方法,要么告诉读者执行以下操作那。
这个属性真的是“必需的”吗?如果是这样,为什么?
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?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
这更多的是 Windows 的要求,而不是 WPF 的要求,并且可以追溯到 .NET 之前的 Windows 窗体和控件的原始设计。
STAThread 指“单线程公寓”,指当前(主)线程使用的线程模型。使用的线程模型决定了其他 .NET 和 COM 应用程序如何与您的应用程序(本质上是其线程)进行通信。与 MTA 线程模型不同,单线程应用程序模型要求单个对象不能同时“驻留在”多个 STA 线程中;并允许仅通过编组为对象在公寓之间传递指向数据的指针。
基本上,通过 [STAThread] 声明,其他应用程序在向您发送数据时就会知道您的线程的策略是什么。 STA模型是Windows线程/应用程序最常见的线程模型;但有时您会遇到某些代码,如果从 STA 模型线程调用,这些代码将无法运行,因为它被设计为以不符合 STA 限制的方式跨线程边界发送/接收数据。预先了解给定线程的单元模型允许 IDE 在编译时捕获这些异常,而不是在运行时尝试跨线程边界使用对象时出现令人讨厌的访问冲突错误。
您可以从 MSDN 文章中了解 STA 和 MTA 线程: http://msdn.microsoft.com/en-us/library/ms680112(VS.85).aspx
请注意,即使是普通的 .NET 应用程序(WPF 之前的版本)也需要在主线程之上声明 [STAThread] ()。
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().
博客条目对此有一个很好的答案。
引用自博客:
There's an excellent answer for this in this blog entry.
Quoting from the blog: