C# 什么是消息泵?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/2222365/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
What is a message pump?
提问by Matt Gutting
In this thread(posted about a year ago) there is a discussion of problems that can come with running Word in a non-interactive session. The (quite strong) advice given there is not to do so. In one post it is stated "The Office APIs all assume you are running Office in an interactive session on a desktop, with a monitor, keyboard and mouse and, most importantly, a message pump." I'm not sure what that is. (I've been programming in C# for only about a year; my other programming experience has primarily been with ColdFusion.)
在此线程(大约一年前发布)中,讨论了在非交互式会话中运行 Word 时可能出现的问题。那里给出的(相当强烈的)建议是不要这样做。在一篇博文中写道:“Office API 都假设您在桌面上的交互式会话中运行 Office,带有显示器、键盘和鼠标,最重要的是,还有一个消息泵。” 我不确定那是什么。(我使用 C# 编程仅一年左右;我的其他编程经验主要是使用 ColdFusion。)
Update:
更新:
My program runs through a large number of RTF files to extract two pieces of information used to construct a medical report number. Rather than try and figure out how the formatting instructions in RTF work, I decided to just open them in Word and pull the text out from there (without actually starting the GUI). Occasionally, the program hiccuped in the middle of processing one file, and left a Word thread open attached to that document (I still have to figure out how to shut that one down). When I re-ran the program, of course I got a notification that there was a thread using that file, and did I want to open a read-only copy? When I said Yes, the Word GUI suddenly popped up from nowhere and started processing the files. I was wondering why that happened; but it looks like maybe once the dialog box popped up the message pump started pushing the main GUI to Windows as well?
我的程序运行了大量的 RTF 文件,以提取用于构建医疗报告编号的两条信息。我没有尝试弄清楚 RTF 中的格式说明是如何工作的,而是决定直接在 Word 中打开它们并从那里拉出文本(而不实际启动 GUI)。偶尔,程序在处理一个文件的过程中会打嗝,并留下一个打开的 Word 线程附加到该文档(我仍然需要弄清楚如何关闭那个)。当我重新运行程序时,当然我收到一个通知,说有一个线程在使用该文件,我是否想打开只读副本?当我说 Yes 时,Word GUI 突然不知从哪里弹出并开始处理文件。我想知道为什么会这样;
回答by Vince Bowdren
Wikipedia suggests it means the program's main Event Loop.
维基百科建议这意味着程序的主要事件循环。
回答by JSB????
The "message pump" is a core part of any Windows program that is responsible for dispatching windowing messages to the various parts of the application. This is the core of Win32 UI programming. Because of its ubiquity, many applications use the message pump to pass messages between different modules, which is why Office applications will break if they are run without any UI.
“消息泵”是任何 Windows 程序的核心部分,负责将窗口消息分派到应用程序的各个部分。这是 Win32 UI 编程的核心。由于其无处不在,许多应用程序使用消息泵在不同模块之间传递消息,这就是为什么 Office 应用程序在没有任何 UI 的情况下运行时会崩溃的原因。
Wikipedia has a basic description.
维基百科有一个基本的描述。
回答by Hogan
John is talking about how the Windows system (and other window based systems - X Window, original Mac OS....) implement asynchronous user interfaces using events via a message system.
John 正在谈论 Windows 系统(以及其他基于窗口的系统 - X Window,原始 Mac OS....)如何通过消息系统使用事件来实现异步用户界面。
Behind the scenes for each application there is a messaging system where each window can send events to other windows or event listeners -- this is implemented by adding a message to the message queue. There is a main loop which always runs looking at this message queue and then dispatching the messages (or events) to the listeners.
每个应用程序的幕后都有一个消息系统,其中每个窗口都可以向其他窗口或事件侦听器发送事件——这是通过向消息队列添加消息来实现的。有一个主循环,它始终运行查看此消息队列,然后将消息(或事件)分派给侦听器。
The Wikipedia article Message loop in Microsoft Windowsshows example code of a basic Windows program -- and as you can see at the most basic level a Windows program is just the "message pump".
维基百科文章Microsoft Windows中的消息循环显示了基本 Windows 程序的示例代码——正如您在最基本的层面上所看到的,Windows 程序只是“消息泵”。
So, to pull it all together. The reason a windows program designed to support a UI can't act as a service is because it needs the message loop running all the time to enable UI support. If you implement it as a service as described, it won't be able to process the internal asynchronous event handling.
所以,把它拉在一起。设计用于支持 UI 的 Windows 程序不能充当服务的原因是因为它需要始终运行消息循环以启用 UI 支持。如果您按照描述将其实现为服务,它将无法处理内部异步事件处理。
回答by Richard Ev
I think that this Channel 9 discussionhas a nice succinct explanation:
我认为第 9 频道的讨论有一个很好的简洁解释:
This process of window communication is made possible by the so-called Windows Message Pump. Think of the Message Pump as an entity that enables cooperation between application windows and the desktop.
这个窗口通信过程是通过所谓的 Windows 消息泵实现的。将消息泵视为实现应用程序窗口和桌面之间协作的实体。
回答by Hans Passant
A message loop is a small piece of code that exists in any native Windows program. It roughly looks like this:
消息循环是存在于任何本机 Windows 程序中的一小段代码。它大致是这样的:
MSG msg;
while (GetMessage(&msg, NULL, 0, 0))
{
TranslateMessage(&msg);
DispatchMessage(&msg);
}
The GetMessage() Win32 API retrieves a message from Windows. Your program typically spends 99.9% of its time there, waiting for Windows to tell it something interesting happened. TranslateMessage() is a helper function that translates keyboard messages. DispatchMessage() ensures that the window procedure is called with the message.
GetMessage() Win32 API 从 Windows 检索消息。您的程序通常在那里花费 99.9% 的时间,等待 Windows 告诉它发生了一些有趣的事情。TranslateMessage() 是翻译键盘消息的辅助函数。DispatchMessage() 确保使用消息调用窗口过程。
Every GUI enabled .NET program has a message loop, it is started by Application.Run().
每个支持 GUI 的 .NET 程序都有一个消息循环,它由 Application.Run() 启动。
The relevance of a message loop to Office is related to COM. Office programs are COM-enabled programs, that's how the Microsoft.Office.Interop classes work. COM takes care of threading on behalf of a COM coclass, it ensures that calls made on a COM interface are always made from the correct thread. Most COM classes have a registry key in the registry that declares their ThreadingModel, by far the most common ones (including Office) use "Apartment". Which means that the only safe way to call an interface method is by making the call from the same thread that created the class object. Or to put it another way: by far most COM classes are not thread-safe.
消息循环与 Office 的相关性与 COM 相关。Office 程序是支持 COM 的程序,这就是 Microsoft.Office.Interop 类的工作方式。COM 代表 COM 协类处理线程,它确保在 COM 接口上进行的调用始终来自正确的线程。大多数 COM 类在注册表中都有一个注册表项来声明它们的 ThreadingModel,到目前为止最常见的类(包括 Office)使用“公寓”。这意味着调用接口方法的唯一安全方法是从创建类对象的同一线程进行调用。或者换一种说法:到目前为止,大多数 COM 类都不是线程安全的。
Every COM enabled thread belongs to a COM apartment. There are two kinds, Single Threaded Apartments (STA) and a Multi Thread Apartment (MTA). An apartment threaded COM class must be created on an STA thread. You can see this back in .NET programs, the entry point of the UI thread of a Windows Forms or WPF program has the [STAThread] attribute. The apartment model for other threads is set by the Thread.SetApartmentState() method.
每个启用 COM 的线程都属于一个 COM 单元。有两种,单线程单元(STA)和多线程单元(MTA)。必须在 STA 线程上创建单元线程 COM 类。您可以在 .NET 程序中看到这一点,Windows 窗体或 WPF 程序的 UI 线程的入口点具有 [STAThread] 属性。其他线程的单元模型由 Thread.SetApartmentState() 方法设置。
Large parts of Windows plumbing won't work correctly if the UI thread is not STA. Notably Drag+Drop, the clipboard, Windows dialogs like OpenFileDialog, controls like WebBrowser, UI Automation apps like screen readers. And many COM servers, like Office.
如果 UI 线程不是 STA,则大部分 Windows 管道将无法正常工作。值得注意的是拖放、剪贴板、Windows 对话框(如 OpenFileDialog)、控件(如 WebBrowser)、UI 自动化应用程序(如屏幕阅读器)。以及许多 COM 服务器,例如 Office。
A hard requirement for an STA thread is that it should never block and must pump a message loop. The message loop is important because that's what COM uses to marshal an interface method call from one thread to another. Although .NET makes marshaling calls easy (Control.BeginInvoke or Dispatcher.BeginInvoke for example), it is actually a very tricky thing to do. The thread that executes the call must be in a well-known state. You can't just arbitrarily interrupt a thread and force it to make a method call, that would cause horrible re-entrancy problems. A thread should be "idle", not busy executing any code that is mutating the state of the program.
STA 线程的一个硬性要求是它永远不应该阻塞并且必须泵送消息循环。消息循环很重要,因为 COM 使用它来将接口方法调用从一个线程编组到另一个线程。尽管 .NET 使封送调用变得容易(例如 Control.BeginInvoke 或 Dispatcher.BeginInvoke),但它实际上是一件非常棘手的事情。执行调用的线程必须处于众所周知的状态。您不能随意中断线程并强制它进行方法调用,这会导致可怕的重入问题。线程应该是“空闲的”,而不是忙于执行任何改变程序状态的代码。
Perhaps you can see where that leads: yes, when a program is executing the message loop, it is idle. The actual marshaling takes place through a hidden window that COM creates, it uses PostMessage to have the window procedure of that window execute code. On the STA thread. The message loop ensures that this code runs.
也许您可以看到这会导致什么:是的,当程序执行消息循环时,它是空闲的。实际的封送处理是通过 COM 创建的隐藏窗口进行的,它使用 PostMessage 让该窗口的窗口过程执行代码。在 STA 线程上。消息循环确保此代码运行。
回答by ConcernedOfTunbridgeWells
In COM, a message pump serialises and de-serialises messages sent between apartments. An apartment is a mini process in which COM components can be run. Apartments come in single threaded and free threaded modes. Single threaded apartments are mainly a legacy system for applications of COM components that don't support multi-threading. They were typically used with Visual BASIC (as this did not support multi-threaded code) and legacy applications.
在COM 中,消息泵对公寓之间发送的消息进行序列化和反序列化。单元是一个微型进程,可以在其中运行 COM 组件。公寓有单线程和自由线程模式。单线程单元主要是用于不支持多线程的 COM 组件应用程序的遗留系统。它们通常与 Visual BASIC(因为它不支持多线程代码)和遗留应用程序一起使用。
I guess that the message pump requirement for Wordstems from either the COM API or parts of the application not being thread safe. Bear in mind that the .NETthreading and garbage collection models don't play nicely with COM out of the box. COM has a very simplistic garbage collection mechanism and threading model that requires you to do things the COM way. Using the standard Office PIAsstill requires you to explicitly shut down COM object references, so you need to keep track of every COM handle created. The PIAs will also create stuff behind the scenes if you're not careful.
我猜想Word的消息泵需求源于 COM API 或应用程序的某些部分不是线程安全的。请记住,.NET线程和垃圾收集模型不能很好地与开箱即用的 COM 配合使用。COM 有一个非常简单的垃圾收集机制和线程模型,它要求您以 COM 的方式做事。使用标准Office PIA仍然需要您显式关闭 COM 对象引用,因此您需要跟踪创建的每个 COM 句柄。如果您不小心,PIA 还会在幕后制造东西。
.NET-COM integration is a whole topic all by itself, and there are even books written on the subject. Even using COM APIs for Office from an interactive desktop application requires you to jump through hoops and make sure that references are explicitly released.
.NET-COM 集成本身就是一个完整的主题,甚至有关于该主题的书籍。即使在交互式桌面应用程序中使用 Office 的 COM API 也需要您跳过障碍并确保显式发布引用。
Office can be assumed to be thread-unsafe, so you will need a separate instance of Word, Excelor other Officeapplications for each thread. You would have to incur the starting overhead or maintain a thread pool. A thread pool would have to be meticulously tested to make sure all COM references were correctly released. Even starting and shutting down instances requires you to make sure all references are released correctly. Failure to dot your i's and cross your t's here will result in large numbers of dead COM objects and even whole running instances of Word being leaked.
可以假定 Office 是线程不安全的,因此您需要为每个线程单独创建 Word、Excel或其他Office应用程序实例。您将不得不承担启动开销或维护线程池。必须仔细测试线程池,以确保正确释放所有 COM 引用。即使启动和关闭实例也需要您确保正确释放所有引用。在这里不加点 i 和交叉 t 将导致大量死 COM 对象甚至 Word 的整个运行实例被泄露。