【发布时间】:2011-06-16 11:41:13
【问题描述】:
我正在尝试创建第二个消息循环以在 C# 中异步处理/过滤低级消息。它的工作原理是创建一个隐藏的表单,将它的 Handle 属性暴露为挂钩,并在单独的线程中运行第二个消息循环。目前我对结果非常满意,但我无法正确退出第二个循环。唯一的解决方法是将 IsBackground 属性设置为 true,因此第二个线程将在主应用程序退出时简单地终止(不处理所有待处理的消息)。
问题是:如何正确退出该消息循环以便第二个 Application.Run() 返回?我尝试了不同的方法来创建单独的 ApplicationContext 并控制各种事件(Application.ApplicationExit、Application.ThreadExit、ApplicationContext.ThreadExit),但它们都因我无法调试的竞争条件而失败。
有什么提示吗?谢谢
这是代码:
public class MessagePump
{
public delegate void HandleHelper(IntPtr handle);
public MessagePump(HandleHelper handleHelper, Filter filter)
{
Thread thread = new Thread(delegate()
{
ApplicationContext applicationContext = new ApplicationContext();
Form form = new Form();
handleHelper(form.Handle);
Application.AddMessageFilter(new MessageFilter(filter));
Application.Run(applicationContext);
});
thread.SetApartmentState(ApartmentState.STA);
thread.IsBackground = true; // <-- The workaround
thread.Start();
}
}
public delegate bool Filter(ref Message m);
internal class MessageFilter : IMessageFilter
{
private Filter _Filter;
public MessageFilter(Filter filter)
{
_Filter = filter;
}
#region IMessageFilter Members
public bool PreFilterMessage(ref Message m)
{
return _Filter(ref m);
}
#endregion // IMessageFilter Members
}
我在主Form构造函数中是这样使用的:
_Completion = new ManualResetEvent(false);
MessagePump pump = new MessagePump(
delegate(IntPtr handle)
{
// Sample code, I did this form twain drivers low level wrapping
_Scanner = new TwainSM(handle);
_Scanner.LoadDs("EPSON Perfection V30/V300");
},
delegate(ref Message m)
{
// Asyncrhronous processing of the messages
// When the correct message is found -->
_Completion.Set();
}
编辑:我的答案中的完整解决方案。
【问题讨论】:
标签: c# hidden window-handles message-pump message-loop