为什么WPF要求将STAThread属性应用于Main方法? [英] Why does WPF require a STAThread attribute to be applied to the Main method?

查看:293
本文介绍了为什么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?

推荐答案

这是Windows的要求,而不是WPF的要求,并且从.NET追溯到Windows窗体和控件的原始设计.

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是指单线程单元",它是指当前(主)线程使用的线程模型.使用的线程模型指示其他.NET和COM应用程序将如何与您的应用程序(以及其固有的线程)进行通信.与MTA线程模型相反,单线程应用程序模型要求一次没有一个对象驻留"在一个以上的STA线程中.并仅允许通过作为对象的编组对象在整个公寓中传递指向数据的指针.

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.

基本上,使用[STAThread]声明,其他应用程序在向您发送数据时将知道线程的策略. STA模型是Windows线程/应用程序最常见的线程模型.但是您有时会遇到某些代码,如果从STA模型化的线程调用该代码将无法运行,因为它旨在以不符合STA限制的方式跨线程边界发送/接收数据.事先了解给定线程的单元模型是什么,IDE就会在编译时捕获这些异常,而在您尝试在运行时跨线程边界使用对象时不会出现讨厌的访问冲突错误.

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.

您可以从以下位置的MSDN文章中了解有关STA和MTA线程的信息:

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

请注意,即使是普通的.NET应用程序(在WPF之前)也需要在main()顶部声明[STAThread].

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

这篇关于为什么WPF要求将STAThread属性应用于Main方法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆