c# - [STAThread] 是做什么的?

标签 c# .net-attributes

我正在学习 C# 3.5,我想知道 [STAThread] 在我们的程序中做了什么?

最佳答案

STAThreadAttribute 本质上是 Windows 消息泵与 COM 组件通信的要求。虽然核心 Windows 窗体不使用 COM,但操作系统的许多组件(例如系统对话框)确实使用了此技术。

MSDN更详细地解释了原因:

STAThreadAttribute indicates that the COM threading model for the application is single-threaded apartment. This attribute must be present on the entry point of any application that uses Windows Forms; if it is omitted, the Windows components might not work correctly. If the attribute is not present, the application uses the multithreaded apartment model, which is not supported for Windows Forms.

This blog post (为什么需要 STAThread?)也很好地解释了该要求。如果您想更深入地了解线程模型如何在 CLR 级别工作,请参阅 this MSDN Magazine article from June 2004 (存档,2009 年 4 月)。

关于c# - [STAThread] 是做什么的?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1361033/

相关文章:

c# - 使用 XmlSerializer 将 DataTable 反序列化为自定义类

c# - 我们如何确保所有 NUnit [Test] 方法都是公开的?

c# - 显示名称属性与显示属性

c# - 在选择中使用 PredicateBuilder

c# - SQL LIKE 命令不包括某些数据

c# - 无法加载文件或程序集“Microsoft.Practices.EnterpriseLibrary.Caching”

c# - 代码契约(Contract) : ContractClassFor when dealing with a generic abstract class?

c# - 最有用的属性

c# - 强制类/方法的属性装饰

c# - 带有 params object[] 构造函数的属性给出了不一致的编译器错误